""" 关于第一个Message1类定义的缺点: ① 书写麻烦 ② 一旦需要再加一个值进行修改,则整个类中的所有内置函数的代码都需要进行相应的修改 ∴ 用第一个Message2就可以把这个问题解决掉 """
class Message1:
def __init__(self, mid: int, text: str):
self.__id: int = mid
self.__text: str = text
@property
def id(self) -> int:
return self.__id
@property
def text(self) -> str:
return self.__text
def __repr__(self):
return f"{self.__class__.__name__}({self.id}, {self.text})"
def __eq__(self, other):
if other.__class__ != self.__class__: # isinstance(other, self):
return NotImplemented
else:
return ((self.id, self.text) == (other.id, other.text))
def __ne__(self, other):
result = self.__eq__(other)
if result is NotImplemented:
return NotImplemented
else:
return not result
def __hash__(self):
return hash((self.__class__, self.id, self.text))
def __lt__(self, other):
if other.__class__ != self.__class__:
return NotImplemented
else:
return self.id < other.id
def __le__(self, other):
if other.__class__ != self.__class__:
return NotImplemented
else:
return self.id <= other.id
def __gt__(self, other):
if other.__class__ != self.__class__:
return NotImplemented
else:
return self.id > other.id
def __ge__(self, other):
if other.__class__ != self.__class__:
return NotImplemented
else:
return self.id >= other.id
@dataclass
class Message2:
id: int = None
text: str = None
age: int = None
if __name__ == '__main__':
m1 = Message1(2, 'hello 2')
m2 = Message1(1, 'hello 1')
m3 = Message2(3, 'hello 3')
print(m3)
print(astuple(m3))
print(asdict(m3))
print(m3.__dir__())
Message2(id=3, text='hello 3', age=None)
(3, 'hello 3', None)
{'id': 3, 'text': 'hello 3', 'age': None}
['id', 'text', 'age', '__module__', '__annotations__', '__dict__', '__weakref__', '__doc__', '__dataclass_params__', '__dataclass_fields__', '__init__', '__repr__', '__eq__', '__hash__', '__str__', '__getattribute__', '__setattr__', '__delattr__', '__lt__', '__le__', '__ne__', '__gt__', '__ge__', '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']
通过m3.__dir__()就可以看到经过@dataclass修饰的数据类,自动初始化了很多内置参数,减少了很多代码的工作量