我在试用Python3.7中的新dataclasses
可以向dataclass
装饰器传递参数,以控制添加到类中的dunder函数。
由于某些原因,装饰器似乎没有为eq=False
参数引发TypeError
。
根据文档:
eq: If true (the default), an __eq__ method will be generated.
This method compares the class as if it were a tuple of its fields, in order.
Both instances in the comparison must be of the identical type
如果我理解正确的话,如果我传递了eq = False
,__eq__
函数将不会被添加,当比较同一个类的两个实例时,应该抛出一个TypeError
。相反,eq
参数似乎没有任何效果。
@dataclass(eq = False)
class Number:
val: int
a = Number(1)
b = Number(2)
c = Number(1)
a == b
False
a == c
False
以上代码不会引发TypeError
,并始终计算为False
。
@dataclass()
class Number:
val: int
a = Number(1)
b = Number(2)
c = Number(1)
a
Number(val = 1)
a == b
False
a == c
True
其他参数(例如:order
、repr
)的行为似乎与预期一致
@dataclass(order = False, repr = False)
class Number:
val:int
a = Number(1)
b = Number(2)
c = Number(1)
a
<__main__.Number object at 0x7fe1036c8b38>
a < b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'Number' and 'Number'
我的理解有什么差距吗?
我正在使用docker镜像python/rc-stretch
发布于 2018-06-29 21:46:06
当您没有定义__eq__
时,__eq__
将解析为object.__eq__
。这就是使用eq=False
创建数据类时所发生的事情。
除非是self is other
,否则object.__eq__(self, other)
为False,即除非两者是同一对象。
https://stackoverflow.com/questions/51102758
复制相似问题