我想比较两个全局数据类的相等性。我更改了其中一个数据类中的字段,但 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()
Run Code Online (Sandbox Code Playgroud)
输出:
Test1: 2017289121504 {} None False
Test2: 2017289119296 {} None True
Are equal? True
Are …Run Code Online (Sandbox Code Playgroud)