python function - parameters

python function - parameters

laboratory

# 演示形参是可变类型
def register(name, hobby, hobby_list=[]):
    hobby_list.append(hobby)
    print(f"{name} prefer {hobby}'")
    print(f"{name} prefer {hobby_list}")


register('nick', 'read')
register('tank', 'zuipao')
register('jason', 'piao')
register('jason', 'piao',[12])

nick prefer read'
nick prefer ['read']
tank prefer zuipao'
tank prefer ['read', 'zuipao']
jason prefer piao'
jason prefer ['read', 'zuipao', 'piao']
jason prefer piao'
jason prefer [12, 'piao']

If for variable parameter, when called, do not pass a value, then he will always point to the same reference deformable. When the incoming parameters this situation will not arise.

1. Function parameters

Location parameter

def zx(x,y)
    print(x)

Argument position

zx(1,2)

Default argument

def zx(x,y=10)

Note: The location must be in the default parameter argument in front of
the keyword arguments

def zx(x,y):
    print(f"{x},{y}")
zx(y=1,x=1)

1,1

Location can be confusing

Variable-length argument 1 (refer to the parameter passed is not fixed)

* Args (tuple received)

def zx(*args):
    print(args)
zx(1,2,3,[12,2],{1:2,2:3})

(1, 2, 3, [12, 2], {1: 2, 2: 3})

* () Break

def zx(x,y,z,c,*args):
    print(x,y,z,c,args)
zx(1,*(1,2,32,12,3),6)

1 1 2 32 (12, 3, 6)

Variable-length argument 2
** kwargs (default parameters received, packaged into a dictionary)

(Dictionary reception)

def func(**kwargw):
    print(kwargw)
func(a=5,b=6,c=7)

{'a': 5, 'b': 6, 'c': 7}

** () break

def func(x, y, z,*args, **kwargs):
    print(x, y, z, kwargs)
func(1, 3, 4,5,**{'a': 1, 'b': 2})

1 3 4 {'a': 1, 'b': 2}

Application of python vararg

def index(name, age, sex):
    print(f"name: {name}, age: {age}, sex: {sex}")


def wrapper(*args, **kwargs):
    print(f"args: {args}")
    print(f"kwargs: {kwargs}")
    index(*args, **kwargs)


wrapper(name='nick', sex='male', age=19)

args: ()
kwargs: {'name': 'nick', 'sex': 'male', 'age': 19}
name: nick, age: 19, sex: male

Guess you like

Origin www.cnblogs.com/zx125/p/11329090.html