任何泛型类型的完美包装器`T`

2024-09-28 21:38:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图为任何泛型类型T创建一个完美的包装器:

import typing

T = typing.TypeVar('T')

class PerfectWrapper(typing.Generic[T], T): # ERROR
    def __init__(self, value: T, index: tuple):
        T.__init__(self, value)
        self.__index = index

    @property
    def index(self):
        return self.__current_index

不幸的是,上面的代码引发了一个错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-48-5c80ceb6eeaf> in <module>
      3 T = typing.TypeVar('T')
      4 
----> 5 class PerfectWrapper(typing.Generic[T], T): # ERROR
      6     def __init__(self, value: T, index: tuple):
      7         T.__init__(self, value)

TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases

我不知道(除了混合两个元类)如何解决这个问题。
我需要从类T继承,以在PerfectWrapper级别上“公开”T的属性/方法

显然,属性:self.__index和方法self.index()是用来用附加信息“扩展”类的。在最基本的版本中,这个包装器可能会将它们注释掉


Tags: ofselftypingindexinitvaluedeferror