首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python3.7:数据类不会为`eq=False`引发`TypeError`

Python3.7:数据类不会为`eq=False`引发`TypeError`
EN

Stack Overflow用户
提问于 2018-06-29 21:21:30
回答 1查看 2K关注 0票数 21

我在试用Python3.7中的新dataclasses

可以向dataclass装饰器传递参数,以控制添加到类中的dunder函数。

由于某些原因,装饰器似乎没有为eq=False参数引发TypeError

根据文档:

代码语言:javascript
复制
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参数似乎没有任何效果。

代码语言:javascript
复制
@dataclass(eq = False)
class Number:
    val: int

a = Number(1)
b = Number(2)
c = Number(1)

a == b
False

a == c
False

以上代码不会引发TypeError,并始终计算为False

代码语言:javascript
复制
@dataclass()
class Number:
    val: int

a = Number(1)
b = Number(2)
c = Number(1)

a
Number(val = 1)

a == b
False

a == c
True

其他参数(例如:orderrepr)的行为似乎与预期一致

代码语言:javascript
复制
@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

EN

回答 1

Stack Overflow用户

发布于 2018-06-29 21:46:06

当您没有定义__eq__时,__eq__将解析为object.__eq__。这就是使用eq=False创建数据类时所发生的事情。

除非是self is other,否则object.__eq__(self, other)为False,即除非两者是同一对象。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51102758

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档