11

从 Python 3.5 开始,您可以使用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,我得到了 False。与super()验证相同。

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

4

0 回答 0