48 lines
1.0 KiB
Python
48 lines
1.0 KiB
Python
#!/usr/bin/env python3
|
||
# -*- coding: utf-8 -*-
|
||
"""
|
||
@File : 函数.py
|
||
@Author : lichao
|
||
@Date : 2024/12/10 19:58
|
||
@Software : PyCharm
|
||
"""
|
||
|
||
|
||
# 函数默认值
|
||
def sub(x=22, y=33):
|
||
return x - y
|
||
|
||
|
||
def add(x, y):
|
||
return x + y
|
||
|
||
|
||
# 调用函数可以指定参数
|
||
print(sub(y=44, x=33))
|
||
|
||
# 最小整数池,在一定范围内,为了节省内存,python会将一些整数对象缓存起来,当再次使用时,直接引用缓存中的对象
|
||
# 对于字符串也存在类似的情况
|
||
print(id(add(3, 2))) # 4381724008
|
||
print(id(add(4, 1))) # 4381724008
|
||
|
||
|
||
def func(x, *args, **kwargs):
|
||
print(x)
|
||
print(args)
|
||
print(kwargs)
|
||
|
||
|
||
# 不定长参数 *args, **kwargs
|
||
# *args: 位置不定长参数,用来将参数打包成元组的形式
|
||
# **kwargs: 关键字不定长参数,用来将参数打包成字典的形式
|
||
func("a", "b", "c", "d", "e", "f", name="lichao", age=22)
|
||
|
||
|
||
def test_fn(a, b, c=10, *args, **kwargs):
|
||
print(a, b, c)
|
||
print(args)
|
||
print(kwargs)
|
||
|
||
|
||
test_fn(1, 2, 3, 4, name="lc")
|