您的位置:首页 > 其它

008: function的定义及调用

2016-01-06 23:37 375 查看
1. 函数由关键字def来做定义

2. 函数内部如果没有返回值,默认返回None

3. 函数接受default参数,The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes.

4. 函数接受关键字传参数,有一个重要的原则:In a function call, keyword arguments must follow positional arguments.

5. Finally, the least frequently used option is to specify that a function can be called with an arbitrary number of arguments. These arguments will be wrapped up in a tuple.

def get_max_number(*args):
max_number = args[0]

for num in args:
if max_number < num:
max_number = num
print(max_number)

get_max_number(1,3,4,2)


6. In the same fashion, dictionaries can deliver keyword arguments with the
**
operator:

7. function同样支持Lambda Expressions(目前只做了解,不做学习)

# basic function
def fib(n):
a, b, result = 0, 1, []
while a < n:
result.append(a)
a, b = b, a+b
return result

print('fib(10)=',fib(10))

# function with default argument values
def sum(x, y=0):
return x + y

print('sum(2)=',sum(2))
print('sum(2,5)=',sum(2,5))
print('sum("2","5")=',sum('2','5'))

# The value of the function name has a type that is recognized by the interpreter as a user-defined function.
# This value can be assigned to another name which can then also be used as a function.
fib_copy = fib
print('fib_copy(10)=',fib_copy(10))

"""
function with default argument values
"""
def full_name(first_name='Miles', middle_name='M', last_name='Yao'):
return first_name + ' ' + middle_name + ' ' + last_name

print('full_name()=',full_name())
print('full_name("Miles")=',full_name('Miles'))
print('full_name("Miles","MM")=',full_name('Miles','MM'))

print("full_name(last_name='Lee', middle_name='XX')=",full_name(last_name='Lee', middle_name='XX'))

polulation = 5

def f_population(arg=polulation):
print(arg)

polulation = 6
# the print value would be 6
f_population()

def f_list(i, _list=[]):
_list.append(i)
return _list

print('f_list(1)=',f_list(1))
print('f_list(2)=',f_list(2))
print('f_list(3)=',f_list(3))

'''
Arbitrary Argument Lists
'''

def concat_a(*args, seperate='/'):
return seperate.join(args)

print("concat_a('hello','world')=",concat_a('hello','world'))
print("concat_a('hello','world', seperate=':'=",concat_a('hello','world', seperate=':'))

'''
dictionaries can deliver keyword arguments with the **-operator:
'''

print('sum(**{"x":12, "y":15})=',sum(**{"x":12, "y":15}))


输出结果:

fib(10)= [0, 1, 1, 2, 3, 5, 8]
sum(2)= 2
sum(2,5)= 7
sum("2","5")= 25
fib_copy(10)= [0, 1, 1, 2, 3, 5, 8]
full_name()= Miles M Yao
full_name("Miles")= Miles M Yao
full_name("Miles","MM")= Miles MM Yao
full_name(last_name='Lee', middle_name='XX')= Miles XX Lee
5
f_list(1)= [1]
f_list(2)= [1, 2]
f_list(3)= [1, 2, 3]
concat_a('hello','world')= hello/world
concat_a('hello','world', seperate=':'= hello:world
sum(**{"x":12, "y":15})= 27
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: