The study of parameter of function in Python(20170908)

来源:互联网 发布:中国与东盟贸易数据 编辑:程序博客网 时间:2024/05/17 02:30

The study of parameter of function in Python(20170908)

positinal parameter

def xxx(e_1):
return e_1*e_1*e_1
e = int(input(‘please enter a number:’))
print(xxx(e))

the e is positional parameter, the function xxx(e_1) only have a parameter

default parameter

def function_name(parameter_1,parameter_2,…)

the first parameter must existen, the second is a default parameter

def register(name,gender,age,major = ‘cs’):
print(name,gender,age,major)
print(register(‘yuhanyu’,’male’,22))
print(register(‘amu’,’female’,23,’math’))

the ‘major’is a default parameter

should notice,the default parameter must point the immutable object

What is immutable object

def add_end(end = None):
if end is None:
end = []
end.append(‘end’)
return end
print(add_end(None))
print(add_end(None))

variable parameter

def x_xx_xxx(*num):
sum = 0
for x in num:
sum = sum + x*x
return sum

e = int(intput(‘please enter a number to test the program:’)

print(x_xx_xxx(1))
print(x_xx_xxx(1,2))
print(x_xx_xxx(1,2,3))

It existens a new way to use the variable parameter

when there are list or tuple

nums = [1,2,3,4]
print(x_xx_xxx(*nums))

the *nums means that the all parameter of the list of nums can be transfered to

the function x_xx_xxx as variable parameter

keyword parameter

example

def personnal_information(name,age,gender,**kwp):
print(‘name=’,name,’age=’,age,’gender=’,gender,’other=’,kwp)
print(personnal_information(‘yuhanyu’,22,’male’))
print(personnal_information(‘amu’,23,’famale’,major = ‘cs’))

that means the keyword parameter can extend the function

the function can recieve more parameter

there is a new way to transfer dict after it is done

more = {‘major’:’cs’,’come_from’:’guilin’}
print(personnal_information(‘yuhanyu’,22,’male’,**more))

named keyword parameter

def(para1,para2,*,nkp1,nkp2):

or def(para1,para2,*variable_parameter,nkp1,nkp2):

must send a parameter to the named keyword parameter

def person(name, age, *, city, job):
print(name, age, city, job)
print(person(‘yuhanyu’,22,city = ‘guilin’,job = ‘cs’))

another way

def person(name, age, *args, city, job):
print(name, age, args, city, job)
person(‘amu’,23,city = ‘guangzhou’,job = ‘cs’)

parameter combination

*args is a variable parameter, recieve a tuple

*kw is a keyword parameter,recieve a dict

可变参数既可以直接传入:func(1, 2, 3),

又可以先组装list或tuple,

再通过args传入:func((1, 2, 3));

关键字参数既可以直接传入:func(a=1, b=2),

又可以先组装dict,

再通过kw传入:func({‘a’: 1, ‘b’: 2})

定义命名的关键字参数在没有可变参数的情况下不要忘了写分隔符*,

否则定义的将是位置参数