1.位置傳遞
def message(name, address):
return 'my name is %s ,my home locate in %s.' %(name,address)
print(message('lily','shanghai'))
調用 message,分別把lily,shanghai 傳遞給name,address函數
2.關鍵字傳遞
def message(name, ago, address):
return 'my name is %s ,%s years ago,my home locate in %s.' %(name, ago, address)
關鍵字傳遞,能夠無視參數順序
print(message(name = 'lily', address = 'shanghai', ago = 12))
關鍵字和位置混用,位置參數要在關鍵字前面
print(message('lily', address = 'shanghai', ago = 12))class
3.默認值參數
def message(name, ago, address='shanghai'):
return 'my name is %s ,%s years ago,my home locate in %s.' %(name, ago, address)
address 該參數沒有給傳遞值,參數賦予默認值
print(message(name='lily', ago=12))
第二次調用函數的時候,address被賦值爲beijing,再也不使用默認值。
print(message(name='lily', address='beijing', ago=12))test
4.包裹傳遞
參數被all收集,type: tuple
def message(*all):
print(all)
print(type(all))
message('a','b','c')dict
參數被collect收集,type: dict
def age(**collect):
print(collect)
print(type(collect))
age(lily=12, xiaoming=13, sare=14)di
結果:
('a', 'b', 'c')
<class 'tuple'>
{'lily': 12, 'xiaoming': 13, 'sare': 14}
<class 'dict'>co
包裹傳遞的關鍵在於定義函數時,在相應元組或字典前加*或**字典
5.解包
tuple1 = [1, 4, 6]
dict1 = {'a': 'test1', 'b': 'test2', 'c': 'test3'}
print('dict1', dict1)
def use(a, b, c):
print(a, b, c)
use(**dict1) # 把字典參數解包 此時至關於關鍵字參數傳遞 名字和函數定義的參數名必需要一一對應
use(*tuple1) #把元組解包 此時至關於位置參數傳遞
結果:
dict1 {'a': 'test1', 'b': 'test2', 'c': 'test3'}
test1 test2 test3
1 4 6參數傳遞