ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Python 3.7:dataclass不会为`eq = False`引发`TypeError`

2019-09-10 21:58:06  阅读:273  来源: 互联网

标签:python python-3-7 python-dataclasses


我在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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有