feat: 添加函数相关内容
This commit is contained in:
parent
faab42e00d
commit
58d8a6c1c6
|
|
@ -1,7 +1,7 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectTasksOptions">
|
||||
<TaskOptions isEnabled="true">
|
||||
<TaskOptions isEnabled="false">
|
||||
<option name="arguments" value="$FilePath$" />
|
||||
<option name="checkSyntaxErrors" value="true" />
|
||||
<option name="description" />
|
||||
|
|
|
|||
|
|
@ -0,0 +1,47 @@
|
|||
#!/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")
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@File : 匿名函数.py
|
||||
@Author : lichao
|
||||
@Date : 2024/12/11 21:11
|
||||
@Software : PyCharm
|
||||
"""
|
||||
|
||||
# 一个匿名函数的使用场景
|
||||
student_list = [
|
||||
{'name': 'Jerry', 'age': 21},
|
||||
{'name': 'Tom', 'age': 20},
|
||||
{'name': 'Mickey', 'age': 22}
|
||||
]
|
||||
|
||||
sorted_list = sorted(student_list, key=lambda x: x['age'])
|
||||
print(sorted_list)
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@File : 拆包.py
|
||||
@Author : lichao
|
||||
@Date : 2024/12/11 16:49
|
||||
@Software : PyCharm
|
||||
"""
|
||||
|
||||
|
||||
def fn_1():
|
||||
return 1, 2, 3
|
||||
|
||||
|
||||
num1, num2, num3 = fn_1()
|
||||
print(num1, num2, num3)
|
||||
|
||||
nums = [11, 22, 33]
|
||||
|
||||
|
||||
def test_fn(a, b, c):
|
||||
print(a, b, c)
|
||||
|
||||
|
||||
# 拆包
|
||||
test_fn(*nums)
|
||||
|
||||
|
||||
def test_fn1(name, age, add):
|
||||
print(name, age, add)
|
||||
|
||||
|
||||
# 拆包字典
|
||||
info = {"name": "lc", "age": 22, "add": "beijing"}
|
||||
test_fn1(**info)
|
||||
Loading…
Reference in New Issue