Is it possible to inherit from class with Generic in Python?

隐身守侯 提交于 2019-12-10 15:56:24

问题


Since Python 3.5 you can use Generics and other interesting stuff described in PEP-0484. I tried that and here's a code I have:

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...

This code works perfectly and does what is expected. Then I decided to extend this class to make some additional work. That's how I did that:

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 ...

To test Pool class I created MyPool which looked like this:

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

Then I put something like mypool = MyPool() and it worked fine. Once I implemented PoolEx, I've updated MyPool to this:

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

And tried to do the same thing: mypool = MyPool(). Unfortunately I got:

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

As you can see, I also put self.__class__.__bases to the log. When I tried to test isinstance(self, PoolEx) and similar with issubclass, I got False. Same as super() verifications.

Is it something with my code or such classes can't have descendants? And if I still want to have PoolEx I have to use composition rather than inheritance.

来源:https://stackoverflow.com/questions/32650416/is-it-possible-to-inherit-from-class-with-generic-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!