如何比较数据类?
How to compare dataclasses?
我想比较两个全局数据类的相等性。我更改了其中一个数据类中的字段,python 仍然坚持告诉我,这些对象是相等的。我不知道内部数据类是如何工作的,但是当我打印 asdict
时,我得到一个空字典...我做错了什么以及如何通过检查其成员是否相等来比较数据类?
我正在使用 Python 3.9.4
from dataclasses import dataclass, asdict
@dataclass
class TestClass:
field1 = None
field2 = False
test1 = TestClass()
test2 = TestClass()
def main():
global test1
global test2
test2.field2 = True
print('Test1: ', id(test1), asdict(test1), test1.field1, test1.field2)
print('Test2: ', id(test2), asdict(test2), test2.field1, test2.field2)
print('Are equal? ', test1 == test2)
print('Are not equal?', test1 != test2)
if __name__ == '__main__':
main()
输出:
Test1: 2017289121504 {} None False
Test2: 2017289119296 {} None True
Are equal? True
Are not equal? False
为了 Python 识别数据类的字段,这些字段应该有 PEP 526 类型注释。
例如:
from typing import Optional
@dataclass
class TestClass:
field1: Optional[str] = None
field2: bool = False
根据该定义比较和 asdict
按预期工作:
In [2]: TestClass(field2=True) == TestClass()
Out[2]: False
In [3]: asdict(TestClass(field2=True))
Out[3]: {'field1': None, 'field2': True}
我想比较两个全局数据类的相等性。我更改了其中一个数据类中的字段,python 仍然坚持告诉我,这些对象是相等的。我不知道内部数据类是如何工作的,但是当我打印 asdict
时,我得到一个空字典...我做错了什么以及如何通过检查其成员是否相等来比较数据类?
我正在使用 Python 3.9.4
from dataclasses import dataclass, asdict
@dataclass
class TestClass:
field1 = None
field2 = False
test1 = TestClass()
test2 = TestClass()
def main():
global test1
global test2
test2.field2 = True
print('Test1: ', id(test1), asdict(test1), test1.field1, test1.field2)
print('Test2: ', id(test2), asdict(test2), test2.field1, test2.field2)
print('Are equal? ', test1 == test2)
print('Are not equal?', test1 != test2)
if __name__ == '__main__':
main()
输出:
Test1: 2017289121504 {} None False
Test2: 2017289119296 {} None True
Are equal? True
Are not equal? False
为了 Python 识别数据类的字段,这些字段应该有 PEP 526 类型注释。
例如:
from typing import Optional
@dataclass
class TestClass:
field1: Optional[str] = None
field2: bool = False
根据该定义比较和 asdict
按预期工作:
In [2]: TestClass(field2=True) == TestClass()
Out[2]: False
In [3]: asdict(TestClass(field2=True))
Out[3]: {'field1': None, 'field2': True}