This article mainly sorts out the parameter passing mechanism of Python functions. The main contents include:
1. The simplest function (no return value, no parameters)
def hello_python():
print("hello python!")
hello_python() # 直接调用
hello python!
2. The simplest function (with return value, no parameters)
def hello_python():
data = "hello python!"
return data # data就是返回值
hello_python()
'hello python!'
Three, with a parameter (no default value)
def hello(data):
result = "hello " + data
return result
hello("python")
'hello python'
Pass in another value:
hello("java")
'hello java'
You can also modify the information of the parameters internally:
def hello_name(name):
result = "Hello " + name.title() + "!"
return result
hello_name("tom")
'Hello Tom!'
hello_name("jack")
'Hello Jack!'
Four, with multiple parameters (no default value)
def information(name, age):
data = "我叫" + name.title() + ", 今年" + str(age) + "岁"
return data
information("tom", 23)
'My name is Tom, I am 23 years old'
information("JACK", 18)
'My name is Jack, I am 18 years old'
Five, parameter setting default value (one parameter)
def hello_name(name="Peter"):
result = "Hello " + name
return result
If no specific value is given for the parameter, the default value is used
hello_name()
'Hello Peter'
Give the parameter an actual value. For example, in the following example, Tom is the actual value; this is the often-called actual parameter
hello_name(name="Tom")
'Hello Tom'
Six, parameter setting default value (multiple parameters)
def information(name="Peter", age=20):
data = "我是" + name + ", 今年" + str(age) + "岁"
return data
1. Use the default values for all:
information()
'I'm Peter, I'm 20 years old'
2. Pass in all the actual values:
information(name="Tom", age=27)
'I'm Tom, I'm 27 years old'
3. Only the actual values of some parameters are passed in; the default values are used for those not passed in:
information(name="Tom")
'I'm Tom, I'm 20 years old'
information(age=18)
'I'm Peter, I'm 18 years old'
7. Some parameters use default values
Parameters with default values must be placed at the end; parameters with default values must be placed at the end
def information(name, age=20):
data = "我是" + name + ", 今年" + str(age) + "岁"
return data
information("Peter") # age默认使用20
'I'm Peter, I'm 20 years old'
information(name="Peter")
'I'm Peter, I'm 20 years old'
information("Peter", age=18)
'I'm Peter, I'm 18 years old'
The following method directly reports an error:
information(age=18, "Peter")
File "<ipython-input-26-2d03cd04a05a>", line 1
information(age=18, "Peter")
^
SyntaxError: positional argument follows keyword argument
information(age=18, name="Peter") # age默认使用20
'I'm Peter, I'm 18 years old'
Important: In the function, the formal parameters without default values must be listed first, and then the formal parameters with default values must be listed:
def information(age=20, name):
data = "我是" + name + ", 今年" + str(age) + "岁"
return data
File "<ipython-input-28-d36363c3194c>", line 1
def information(age=20, name):
^
SyntaxError: non-default argument follows default argument
How to understand that parameters with default values must be placed at the end?
Below is a custom get_name function, passing in the first, last and middle names, but not everyone has a middle name:
def get_name(first_name, last_name, middle_name=''):
if middle_name: # 如果存在中间名字
name = first_name + middle_name + last_name
else:
name = first_name + last_name
return name
get_name(first_name="张", last_name="飞", middle_name='')
'Zhang Fei'
get_name(first_name="孙", last_name="空", middle_name='悟')
'Monkey King'
If the middle_name is not passed, the result is definitely not what we want:
get_name(first_name="孙", last_name="空")
'Sun Kong'
8. Positional arguments
def get_information(name, age):
data = "我是" + name + ", 今年" + str(age) + "岁"
return data
get_information("Tom", 20)
'I'm Tom, I'm 20 years old'
get_information("20","Tom") # 一定要按照原来形参的顺序传递
'I'm 20, Tom's this year'
The above result is definitely not what we want
9. Keyword arguments
When passing arguments using keywords, the order does not matter:
get_information(name="Tom", age=20)
'I'm Tom, I'm 20 years old'
get_information(age=20, name="Tom")
'I'm Tom, I'm 20 years old'
10. Mixed use of positional arguments and keyword arguments
get_information("Tom", age=20)
'I'm Tom, I'm 20 years old'
When using it, it is still necessary to follow the order in the original function, otherwise an error will be reported:
get_information(age=20,"Tom")
File "<ipython-input-39-bc20bc544493>", line 1
get_information(age=20,"Tom")
^
SyntaxError: positional argument follows keyword argument
11. Advanced: use of *args
Sometimes our implementation does not know how many parameters the function needs to accept. At this time, we can use *args
or **kwargs
to collect any number of parameters.
The use introduced first *args
. Suppose we want to convert the height of each student in a class into meters, that is, divide by 100:
def height(*args):
data = args
return data
height()
By default the function collects an empty tuple:
()
height(178)
When passing in data, it is expressed in the form of tuples:
(178,)
height(178,189)
(178, 189)
def height(*args):
for data in args: # 对args中的元素进行循环操作
print("身高是: {}m".format(data / 100))
height(189,180,167,172) # 调用
Height: 1.89m
Height: 1.8m
Height: 1.67m
Height: 1.72m
12. Advanced: use of **kwargs
**kwargs
Allows passing variable-length key-value pairs as arguments to a function
def information(**kwargs):
data = kwargs
print(data)
Collected by default is a dictionary:
information(name="Peter")
{'name': 'Peter'}
information(name="Peter", age=23)
{'name': 'Peter', 'age': 23}
def information(**kwargs):
for k, v in kwargs.items():
print("{0} == {1}".format(k,v))
information(name="Peter")
name == Peter
information(name="Peter", age=23)
name == Peter
age == 23
information(name="Peter", age=23, height=175)
name == Peter
age == 23
height == 175
13. Advanced: *args
use with formal parameters
def fun(x, *args):
print("x:", x)
print("args:", args)
fun(1)
x: 1
args: ()
fun(1,2)
x: 1
args: (2,)
fun(1,2,3,4)
x: 1
args: (2, 3, 4)
fun(1,2,3,4,"Peter")
x: 1
args: (2, 3, 4, 'Peter')
14. Advanced: Use **kwargs with formal parameters
def fun(x, **kwargs):
print("x:", x)
print("kwargs:", kwargs)
fun(1)
x: 1
kwargs: {}
fun(1,name="Peter")
x: 1
kwargs: {'name': 'Peter'}
fun(1,name="Peter",age=23)
x: 1
kwargs: {'name': 'Peter', 'age': 23}
15. Advanced: formal parameters + *args
+ **kwargs
combined use
def fun(x, *args, **kwargs):
print("x:", x)
print("args:", args)
print("kwargs:", kwargs)
fun(1)
x: 1
args: ()
kwargs: {}
fun(1,2,3)
x: 1
args: (2, 3)
kwargs: {}
fun(1,name="Peter",age=23)
x: 1
args: ()
kwargs: {'name': 'Peter', 'age': 23}
fun(1,2,3,name="Peter",age=23)
x: 1
args: (2, 3)
kwargs: {'name': 'Peter', 'age': 23}
kwargs = {"name":"Peter","age":23}
fun(1,2,3,**kwargs)
x: 1
args: (2, 3)
kwargs: {'name': 'Peter', 'age': 23}