函数定义
def my_abs(x):
return x if x >=0 else -x
if __name__ == '__main__':
print(my_abs(5))
print(my_abs(-5))
输出:
5
5
函数的返回
def return_item(res):
return res
print("return:", return_item(1))
print("type:", type(return_item(1)))
print("return:", return_item("A"))
print("type:", type(return_item("A")))
输出:
return: 1
type: <class 'int'>
return: A
type: <class 'str'>
函数的多值返回
def return_items():
return 1, 2, 3
a, b, c = return_items()
print("abc:", a, b, c)
print("return:", return_items())
print("type:", type(return_items()))
输出:
abc: 1 2 3
return: (1, 2, 3)
type: <class 'tuple'>
参数类型检查
def max(num1, num2):
if not isinstance(num1, int) or not isinstance(num2, int):
raise TypeError("must be int!")
return num1 if num1 > num2 else num2
if __name__ == '__main__':
print(max(1, 2))
print(max("a", 2))
输出:
Traceback (most recent call last):
File "C:/Users/focks/OneDrive/CrapCode/Python/TestAll/function.py", line 16, in <module>
print(max("a", 2))
File "C:/Users/focks/OneDrive/CrapCode/Python/TestAll/function.py", line 10, in max
raise TypeError("must be int!")
TypeError: must be int!
2
函数的默认参数
def hello(name="world"):
print("hello,", name, "!")
if __name__ == '__main__':
hello()
hello("god fish")
输出:
hello, world !
hello, god fish !
可变参数
可变参数传入的是一个tuple或list。
def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
if __name__ == '__main__':
print(calc(1, 2, 3, 4))
num = [1, 2, 3, 4]
print(calc(*num))
输出:
30
30
关键字参数
关键字参数传入的是一个字典。
def person(name, age, **kw):
print('name:', name, 'age:', age, 'other:', kw)
if __name__ == '__main__':
person("godfish", 10, school="hqu", color="green")
godfish = {'school':"hqu", 'color':"green"}
person("godfish", 10, **godfish)
输出:
name: godfish age: 10 other: {'school': 'hqu', 'color': 'green'}
name: godfish age: 10 other: {'school': 'hqu', 'color': 'green'}
命名关键字参数
命名关键字参数传入的是一个字典,字典的键必须在规定范围内,且规定范围内的所有键都必须要传入。
def person(name, age, *, city, job):
print(name, age, city, job)
if __name__ == '__main__':
person("godfish", 10, city="green city", job="wang")
godfish = {'city': "green city", 'job': "wang"}
person("godfish", 10, **godfish)
# person("godfish", 10, like="hhh")
# ->TypeError: person() got an unexpected keyword argument 'like'
# person("godfish", 10, city="green city")
# ->TypeError: person() missing 1 required keyword-only argument: 'job'
输出:
godfish 10 green city wang
godfish 10 green city wang
参数组合
节选自函数的参数。
在Python中定义函数,可以用必选参数、默认参数、可变参数、关键字参数和命名关键字参数,这5种参数都可以组合使用。但是请注意,参数定义的顺序必须是:必选参数、默认参数、可变参数、命名关键字参数和关键字参数。
比如定义一个函数,包含上述若干种参数:
def f1(a, b, c=0, *args, **kw):
print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)
def f2(a, b, c=0, *, d, **kw):
print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)
在函数调用的时候,Python解释器自动按照参数位置和参数名把对应的参数传进去。
>>> f1(1, 2)
a = 1 b = 2 c = 0 args = () kw = {}
>>> f1(1, 2, c=3)
a = 1 b = 2 c = 3 args = () kw = {}
>>> f1(1, 2, 3, 'a', 'b')
a = 1 b = 2 c = 3 args = ('a', 'b') kw = {}
>>> f1(1, 2, 3, 'a', 'b', x=99)
a = 1 b = 2 c = 3 args = ('a', 'b') kw = {'x': 99}
>>> f2(1, 2, d=99, ext=None)
a = 1 b = 2 c = 0 d = 99 kw = {'ext': None}
最神奇的是通过一个tuple和dict,你也可以调用上述函数:
>>> args = (1, 2, 3, 4)
>>> kw = {'d': 99, 'x': '#'}
>>> f1(*args, **kw)
a = 1 b = 2 c = 3 args = (4,) kw = {'d': 99, 'x': '#'}
>>> args = (1, 2, 3)
>>> kw = {'d': 88, 'x': '#'}
>>> f2(*args, **kw)
a = 1 b = 2 c = 3 d = 88 kw = {'x': '#'}
所以,对于任意函数,都可以通过类似func(*args, **kw)
的形式调用它,无论它的参数是如何定义的。