我喜欢Python 3.6中的typing.NamedTuple
。但通常情况下,namedtuple
包含一个不可清除的属性,我想将它用作dict
密钥或set
成员。如果namedtuple
类使用对象标识(id()
用于__eq__
和__hash__
)是有意义的,那么将这些方法添加到类中可以正常工作。
但是,我现在在我的代码中有几个地方有这种模式,我想摆脱样板__eq__
和__hash__
方法定义。我知道namedtuple
不是常规课程,我也无法弄清楚如何使这个工作。
这是我尝试过的:
from typing import NamedTuple
class ObjectIdentityMixin:
def __eq__(self, other):
return self is other
def __hash__(self):
return id(self)
class TestMixinFirst(ObjectIdentityMixin, NamedTuple):
a: int
print(TestMixinFirst(1) == TestMixinFirst(1)) # Prints True, so not using my __eq__
class TestMixinSecond(NamedTuple, ObjectIdentityMixin):
b: int
print(TestMixinSecond(2) == TestMixinSecond(2)) # Prints True as well
class ObjectIdentityNamedTuple(NamedTuple):
def __eq__(self, other):
return self is other
def __hash__(self):
return id(self)
class TestSuperclass(ObjectIdentityNamedTuple):
c: int
TestSuperclass(3)
"""
Traceback (most recent call last):
File "test.py", line 30, in <module>
TestSuperclass(3)
TypeError: __new__() takes 1 positional argument but 2 were given
"""
有没有办法我不需要在每个NamedTuple
重复这些方法,我需要'对象身份'?
NamedTuple
类语法的神奇来源是它的metaclass NamedTupleMeta
,behind the scene,NamedTupleMeta.__new__
为你创建了一个新类,而不是典型的类,而是由collections.namedtuple()
创建的类。
问题是,当NamedTupleMeta
创建新的类对象时,它忽略了基类,你可以检查TestMixinFirst
的MRO,没有ObjectIdentityMixin
:
>>> print(TestMixinFirst.mro())
[<class '__main__.TestMixinFirst'>, <class 'tuple'>, <class 'object'>]
你可以扩展它来处理基类:
import typing
class NamedTupleMetaEx(typing.NamedTupleMeta):
def __new__(cls, typename, bases, ns):
cls_obj = super().__new__(cls, typename+'_nm_base', bases, ns)
bases = bases + (cls_obj,)
return type(typename, bases, {})
class TestMixin(ObjectIdentityMixin, metaclass=NamedTupleMetaEx):
a: int
b: int = 10
t1 = TestMixin(1, 2)
t2 = TestMixin(1, 2)
t3 = TestMixin(1)
assert hash(t1) != hash(t2)
assert not (t1 == t2)
assert t3.b == 10