Python 3.7:dataclass不会为`eq = False`引发`TypeError`
作者:互联网
我在Python 3.7中尝试新的数据类
可以传递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 image python / rc-stretch
解决方法:
在python3.7中,给出了以下数据类定义
@dataclass(eq=False)
class Number:
val: int
Number(1)== Number(1)的预期结果为False.这是正确的,因为设置eq = True只会覆盖the default python-object equality function,在这种情况下,它仅检查相同的引用(与is相同).
dataclass specification在这里有点缺乏.它解释了eq参数
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. […]
但是为了理解你遇到的问题,你还需要知道基本的python对象已经提供了一个__eq__函数:
>>> class A: pass
...
>>> dir(A())
['__class__', '__delattr__', ... '__eq__', ...] # has __eq__ already
标签:python,python-3-7,python-dataclasses 来源: https://codeday.me/bug/20190910/1801790.html