【python学习笔记】函数参数传递方法[Python基础]

python

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))

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))

4.包裹传递

参数被all收集,type: tuple

def message(*all):

print(all)

print(type(all))

message("a","b","c")

参数被collect收集,type: dict

def age(**collect):

print(collect)

print(type(collect))

age(lily=12, xiaoming=13, sare=14)

结果:

("a", "b", "c")

<class "tuple">

{"lily": 12, "xiaoming": 13, "sare": 14}

<class "dict">

包裹传递的关键在于定义函数时,在相应元组或字典前加*或**

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

以上是 【python学习笔记】函数参数传递方法[Python基础] 的全部内容, 来源链接: utcz.com/z/530398.html

回到顶部