如何应用特殊方法' Mixin'打字.NamedTuple

时间:2017-11-16 21:12:57

标签: python python-3.6 namedtuple

我喜欢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;在?

1 个答案:

答案 0 :(得分:5)

NamedTuple类语法的神奇来源是metaclass NamedTupleMetabehind the sceneNamedTupleMeta.__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