mirror of
https://github.com/jaywcjlove/reference.git
synced 2025-08-25 08:05:12 +08:00
doc: Update python.md (#986)
增加高阶函数sorted reduce map以及偏函数,增加类属性的访问控制和验证
This commit is contained in:
101
docs/python.md
101
docs/python.md
@@ -1394,6 +1394,33 @@ print(Yoki.legs) # => 4
|
||||
Yoki.sound() # => Woof!
|
||||
```
|
||||
|
||||
### 属性封装与访问控制
|
||||
|
||||
实现计算属性、只读属性和验证逻辑。
|
||||
```python
|
||||
class Person:
|
||||
def __init__(self, age):
|
||||
self._age = age # 约定:_age 为内部属性
|
||||
|
||||
@property
|
||||
def age(self):
|
||||
"""获取年龄的方法,伪装成属性"""
|
||||
return self._age
|
||||
|
||||
@age.setter
|
||||
def age(self, value):
|
||||
"""设置年龄的方法,添加验证逻辑"""
|
||||
if value < 0:
|
||||
raise ValueError("年龄不能为负数")
|
||||
self._age = value
|
||||
|
||||
# 使用示例
|
||||
p = Person(30)
|
||||
print(p.age) # 直接访问属性,无需括号 → 30
|
||||
p.age = 31 # 赋值操作调用 @age.setter → 验证通过
|
||||
p.age = -5 # 抛出 ValueError: 年龄不能为负数
|
||||
```
|
||||
|
||||
Python 数据模型
|
||||
--------
|
||||
|
||||
@@ -1813,6 +1840,80 @@ else: # try/except 块的可选子句。 必须遵循除块
|
||||
finally: # 在所有情况下执行
|
||||
print("我们可以在这里清理资源")
|
||||
```
|
||||
### 高阶函数map
|
||||
|
||||
将一个函数应用到可迭代对象(如列表)的每个元素上,并返回一个新的迭代器。
|
||||
```python
|
||||
def square(x):
|
||||
return x ** 2
|
||||
|
||||
使用 map 函数
|
||||
numbers = [1, 2, 3, 4]
|
||||
result = map(square, numbers)
|
||||
|
||||
转换为列表查看结果
|
||||
print(list(result)) # 输出: [1, 4, 9, 16]
|
||||
```
|
||||
|
||||
### 高阶函数sorted
|
||||
|
||||
对可迭代对象进行排序,返回一个新的已排序列表(原对象不变)
|
||||
```python
|
||||
# 按照分数排序
|
||||
users = [
|
||||
{"name": "Alice", "score": 95, "time": "2023-01-15 10:30:00"},
|
||||
{"name": "Bob", "score": 88, "time": "2023-01-15 09:45:00"},
|
||||
{"name": "Charlie", "score": 95, "time": "2023-01-14 15:20:00"},
|
||||
{"name": "David", "score": 85, "time": "2023-01-16 11:10:00"}
|
||||
]
|
||||
# reverse=True代表降序排序
|
||||
sorted_users = sorted(users, key=lambda x: x["score"], reverse=True)
|
||||
|
||||
# 输出结果
|
||||
for user in sorted_users:
|
||||
print(f"{user['name']}: {user['score']}")
|
||||
|
||||
# 结果:
|
||||
# Alice: 95
|
||||
# Charlie: 95
|
||||
# Bob: 88
|
||||
# David: 85
|
||||
```
|
||||
|
||||
### 高阶函数reduce
|
||||
|
||||
将一个二元函数(接受两个参数的函数)累积应用到可迭代对象的元素上,最终合并为单个值
|
||||
```python
|
||||
from functools import reduce
|
||||
|
||||
# 定义一个乘法函数
|
||||
def multiply(x, y):
|
||||
return x * y
|
||||
|
||||
# 使用 reduce 函数
|
||||
numbers = [2, 3, 4, 5]
|
||||
result = reduce(multiply, numbers)
|
||||
|
||||
print(result) # 输出: 120(2×3×4×5=120)
|
||||
```
|
||||
### 偏函数
|
||||
|
||||
固定原函数的某些参数,生成新函数
|
||||
```python
|
||||
from functools import partial
|
||||
|
||||
# 原函数:计算 x 的 y 次幂
|
||||
def power(x, y):
|
||||
return x ** y
|
||||
|
||||
# 创建偏函数,固定 y=2(即平方函数)
|
||||
square = partial(power, y=2)
|
||||
|
||||
# 调用偏函数
|
||||
print(square(5)) # 输出: 25 (5²)
|
||||
print(square(10)) # 输出: 100 (10²)
|
||||
```
|
||||
|
||||
|
||||
### pyenv & pipenv
|
||||
<!--rehype:wrap-class=col-span-3-->
|
||||
|
Reference in New Issue
Block a user