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