是否可以在Python中使用Generic继承类?

时间:2015-09-18 11:03:28

标签: python generics inheritance descendant python-3.5

从Python 3.5开始,您可以使用Generics和PEP-0484中描述的其他有趣内容。 我试过了,这是我的代码:

from typing import TypeVar, Generic, Optional
...

_T = TypeVar('T')
_S = TypeVar('S')


class Pool(Generic[_S, _T]):
    def __init__(self) -> None:
        self.pool = dict()

    ... getters and setters here...

此代码可以完美地运行并完成预期的操作。然后我决定扩展这个类来做一些额外的工作。这就是我如何做到的:

class PoolEx(Pool[_S, _T]):

    ARGUMENTS = []

    def __init__(self) -> None:
        print("self=", self, self.__class__.__bases__)
        super(PoolEx, self).__init__()
        self.arguments_pool = dict()

    ... other code here ...

要测试Pool我创建MyPool的课程,如下所示:

class MyPool(Pool[str, Hello]):
    pass

然后我放了像mypool = MyPool()这样的东西,它运行正常。实施PoolEx后,我已将MyPool更新为:

class MyPool(PoolEx[str, Hello]):
    ARGUMENTS = ['name', 'surname']

并尝试做同样的事情:mypool = MyPool()。不幸的是我得到了:

self= <__main__.MyPool object at 0x1068644e0> (__main__.PoolEx[str, __main__.Hello],)
Traceback (most recent call last):
  File "/usr/local/Cellar/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/lib/python3.5/runpy.py", line 170, in _run_module_as_main
    "__main__", mod_spec)
  File "/usr/local/Cellar/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/lib/python3.5/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/Users/8bitjoey/.../utils/pool.py", line 141, in <module>
    mypool = MyPool()
  File "/Users/8bitjoey/.../utils/pool.py", line 52, in __init__
    super(PoolEx, self).__init__()
TypeError: super(type, obj): obj must be an instance or subtype of type

如您所见,我还将self.__class__.__bases放入日志中。当我尝试测试isinstance(self, PoolEx)并与issubclass类似时,我得到了假。与super()验证相同。

这是我的代码还是这样的类不能有后代?如果我还想拥有PoolEx,我必须使用合成而不是继承。

0 个答案:

没有答案