def
def a(b,c=3,d='hi'):
print(c)
python的函数定义没有类型的限制,在c中,函数定义首先要求定义返回类型,然后->参数的数据类型->内存中预留出足够空间,当函数体入栈时,从这一块内存中按照参数的数据类型,顺序读取出各个参数。
但是python把这些都做了简化,以动态语言特有的方式,宽松的对待函数参数的申明,无论默认的参数数据是什么类型,最终都可以随意赋值,但是参数的输入顺序则不可避免的需要遵守,顺序很重要的原因不必说。
在处理参数错误时,需要由程序员操心try的问题,这是动态语言的缺点,方便编写的同时,却使得某些逻辑变得更复杂。
Important warning: 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. For example, the following function accumulates the arguments passed to it on subsequent calls:
def f(a, L=[]):
L.append(a)
return L
print(f(1))
print(f(2))
print(f(3))
This will print
[1]
[1, 2]
[1, 2, 3]
If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
网友评论