设为首页 加入收藏

TOP

Python自定义函数基础(一)
2017-04-07 10:24:52 】 浏览:6720
Tags:Python 定义 函数 基础

1 格式:
    def functionName(参数列表):
                  方法体
例子1:
>>>def greet_user():
        print(“hello”)
>>>greet_user()
hello


 
例子2:
>>>def greet_user(username): #username形参
      print(“hello,”+ username+“!”)
>>>greet_user(“zhangsan”)#zhangsan 实参
hello, zhangsan!


鉴于函数定义中可能包含多个形参,因此在函数调用中也可能包含多个实参。向函数中传递实参的方式很多,可以使用位置实参,这要求实参的顺序和形参的顺序相同;也可以使用关键字形参,其中的每个实参都有变量名和值组成;还可以使用列表和字典。
                                                     
(1)位置实参
        要求实参的顺序和形参的顺序相同
        例子:
       
def describe_pet(animal_type,pet_name):
                  print(“\n I have a”+animal_type+”.”)
                  print(“My ”+animal_type+”’sname is ”+pet_name+”.”)
 describe_pet(‘hamster’,’harry’)


当两个参数的位置交换后,表达的意思就会出现错误。
这种传参方式应该是最好理解的,大部分语言都是这种传参方式。
(2)默认参数
编写函数时,可给每个形参指定默认值。在调用函数中给形参提供了实参时,Python将使用指定实参,否则使用默认值。
123 def describe_pet(pet_name,animal_type=‘dog’):
    print(“\n I have a”+animal_type+”.”)
    print(“My ”+animal_type+”’sname is ”+pet_name+”.”)


注意:在使用默认参数时,在形参列表中必须先列出没有默认值的形参,再列出有默认值的形参。
当然,默认值不一定是字符串,数字等,同时也支持各种序列。
def f(a, L=[]):
    L.append(a)
    return L
 
print(f(1))
print(f(2))
print(f(3))


输出结果为
[1]
[1, 2]
[1, 2, 3]
 
如果你不想调用之间共享的默认设置,你可以这样写
def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L


感觉有点像java中单例模式中的懒汉式,虽然不能这么比。
 
(3)关键字实参
        关键字实参是传递给函数的 名称-值对。你直接在实参中将名称和值关联起来,因此向函数传递实参时不会混淆
def parrot(voltage, state='a stiff', action='voom',type='Norwegian Blue'):
    print("--This parrot wouldn't", action, end=' ')
    print("ifyou put", voltage, "volts through it.")
    print("--Lovely plumage, the", type)
    print("--It's", state, "!")
 
parrot(1000)                                          # 1positional argument
parrot(voltage=1000)                                  # 1 keywordargument
parrot(voltage=1000000,action='VOOOOOM')            # 2 keywordarguments
parrot(action='VOOOOOM',voltage=1000000)            # 2 keywordarguments
parrot('amillion', 'bereft of life', 'jump')        # 3 positional arguments
parrot('athousand', state='pushing up the daisies') # 1 positional, 1 keyword


执行后的结果
>>>
===========RESTART: D:/python/pythonLearning/KeywordArguments.py ===========
-- This parrotwouldn't voom if you put 1000 volts through it.
-- Lovelyplumage, the Norwegian Blue
-- It's a stiff!
-- This parrotwouldn't voom if you put 1000 volts through it.
-- Lovelyplumage, the Norwegian Blue
-- It's a stiff!
-- This parrotwouldn't VOOOOOM if you put 1000000 volts through it

首页 上一页 1 2 3 下一页 尾页 1/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇C++实现动态顺序表 下一篇Java通信实战:编写自定义通信协议..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目