def
def a(b,c=3,d='hi'):
print(c)
python的函數(shù)定義沒有類型的限制,在c中,函數(shù)定義首先要求定義返回類型,然后->參數(shù)的數(shù)據(jù)類型->內(nèi)存中預(yù)留出足夠空間,當(dāng)函數(shù)體入棧時,從這一塊內(nèi)存中按照參數(shù)的數(shù)據(jù)類型,順序讀取出各個參數(shù)。
但是python把這些都做了簡化,以動態(tài)語言特有的方式,寬松的對待函數(shù)參數(shù)的申明,無論默認(rèn)的參數(shù)數(shù)據(jù)是什么類型,最終都可以隨意賦值,但是參數(shù)的輸入順序則不可避免的需要遵守,順序很重要的原因不必說。
在處理參數(shù)錯誤時,需要由程序員操心try的問題,這是動態(tài)語言的缺點,方便編寫的同時,卻使得某些邏輯變得更復(fù)雜。
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