https://docs.python.org/zh-cn/3/library/dataclasses.html
https://peps.python.org/pep-0526/
https://peps.python.org/pep-0557/
dataclass
简单示例
from dataclasses import dataclass
@dataclass
class User:
name: str
age: int
if __name__ == '__main__':
response_json = {'name': 'python', 'age': 32}
user = User(**response_json)
print(user.name, user.age) # python 32
不用使用 dataclass
也可以
class User:
def __init__(self, name: str, age: int):
self.name = name
self.age = age
if __name__ == '__main__':
response_json = {'name': 'python', 'age': 32}
user = User(**response_json)
print(user.name, user.age)
User
显得稍显麻烦,不过这里很简单,倒也无所谓。
dataclass
优势
dataclass
比直接使用class
书写更简洁, 看起来一目了然dataclass
自动实现实用方法,比如__repr__
Pycharm
的完全代码提示
dataclass
的不足
不支持嵌套
from dataclasses import dataclass
@dataclass
class Info:
sex: str
phone: str
address: str = None
@dataclass
class User:
name: str
age: int
info: Info = None
if __name__ == '__main__':
response_json = {
'name': 'python',
'age': 32,
'info': {
'sex': '',
'phone': '',
'address': 'https://python.org/'
},
}
user = User(**response_json)
# 显然这里我们期望的不是 dict
assert isinstance(user.info, dict)
不支持扩展字段
from dataclasses import dataclass
@dataclass
class User:
name: str
age: int
if __name__ == '__main__':
response_json = {
'name': 'python',
'age': 32,
'address': 'https://python.org/'
}
# TypeError: __init__() got an unexpected keyword argument 'address'
user = User(**response_json)
使用 datclass
库弥补这些不足
https://github.com/foyoux/datclass
pip install datclass
datclass
简单示例
from dataclasses import dataclass
from datclass import DatClass
@dataclass
class Info(DatClass):
sex: str
phone: str
address: str = None
@dataclass
class User(DatClass):
name: str
age: int
info: Info = None
if __name__ == '__main__':
response_json = {
'name': 'python',
'age': 32,
'info': {
'sex': '',
'phone': '',
'address': 'https://python.org/',
'field': 'extra'
},
}
user = User(**response_json)
assert isinstance(user.info, Info)
assert isinstance(user.info, Info)
print(user.info.address) # https://python.org/
datclass
附带一个命令行命令用以自动生成 DatClass
→ datclass