![](/img/trans.png)
[英]Dataclass in python does not raise error when the class variable is assigned as a list (but does with typing hints)
[英]Python 3.7: dataclass does not raise `TypeError` for `eq=False`
我正在嘗試 Python 3.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 image python/rc-stretch
在python3.7中,給出如下數據類定義
@dataclass(eq=False)
class Number:
val: int
Number(1) == Number(1)
的預期結果是False
。 這是正確的,因為設置eq = True
只覆蓋默認的 python-object 相等函數,它只檢查相同的引用(與Number(1) is Number(1)
相同, Number(1) is Number(1)
,在這種情況下可能更明顯地評估為false
)。
這里有點缺乏數據類規范。 它解釋了eq
參數
eq:如果為 true(默認值),將生成一個 __eq__ 方法。 此方法按順序將類作為其字段的元組進行比較。 [...]
但是為了理解你遇到的問題,你還需要知道基本的python對象已經帶有一個__eq__
函數:
>>> class A: pass
...
>>> dir(A())
['__class__', '__delattr__', ... '__eq__', ...] # has __eq__ already
當您不定義__eq__
, __eq__
將解析為object.__eq__
。 當您使用eq=False
創建數據類時,就會發生這種情況。
object.__eq__(self, other)
是 False 除非self is other
,即除非兩者是同一個對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.