5-8-新特性
2020年12月20日小于 1 分钟
1. Dataclass
传统面向对象编程如下所示:
class User:
def __init__(self, name: str, age: int, favourite_ic: str) -> None:
self.name = name
self.age = age
self.favourite_ic = favourite_ic
def is_adult(self) -> bool:
"""Return True if user is an adult, else False."""
return self.age >= 18
if __name__ == '__main__':
john = User('John', 29, '555')
print(john)
# prints "<__main__.User object at 0x0076E610>"
<__main__.User object at 0x000002B80BF125F8>
编写这种类时具有通用的模式,Python 3.7 中引入了 dataclass,使得这种类更容易声明,更加可读。
只需要使用 @dataclass 装饰类,对 self 的赋值就会自动发生,类型注解是强制的。
from dataclasses import dataclass
@dataclass
class User:
name: str
age: int
favourite_ic: str
def is_adult(self) -> bool:
"""Return True if user is an adult, else False."""
return self.age >= 18
if __name__ == '__main__':
john = User('John', 29, '555')
print(john)
# prints "User(name='John', age=29, favourite_ic='555')"