我喜欢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
中重复使用我需要的对象标识&#39;在?
答案 0 :(得分:5)
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