Skip to content
鼓励作者:欢迎打赏犒劳

python函数

函数定义

python
def foo():
    print('hello, world!')

# 调用
foo()

默认参数

python
def foo(name = '小米',age = 12):
    print(f'hello, world! , {name} : {age}')

# 调用
foo( name = '华为',age =1)

可变位置参数

python
def calc(*args):
   print(type(args))
   for i in args:
       print(i)

calc(1,2,3)
# <class 'tuple'>
# 1
# 2
# 3

# 自动解包
calc(*[11,22,33])
# <class 'tuple'>
# 11
# 22
# 33

可变关键字参数

python
# 可变的关键字传参
def fun2(**kwargs):
    print(type (kwargs))
    for key,value in kwargs.items():
        print(key,'-----',value)


fun2(name='小米',age=1)
# <class 'dict'>
# name ----- 小米
# age ----- 1

## 自动解包
obj = {"name":"哈哈"}
fun2(**obj)
# <class 'dict'>
# name ----- 哈哈

如有转载或 CV 的请标注本站原文地址