Reputation: 12697
I have a "partial" class that requires some mixin for its functionality (I want to do it with inheritance for performance and simplicity reasons). Can I declare that my class is going to need new methods?
Apparently the following guess does not work ("Can't instantiate abstract class"):
from abc import abstractmethod, ABCMeta
class A(metaclass=ABCMeta):
@abstractmethod
def a(self):
pass
class B:
def a(self):
return 12
class C(A, B):
pass
c = C()
Here A
tries to declare that its other methods need a()
to work.
(Python 3)
Any suggestions to the declare that?
Upvotes: 0
Views: 235
Reputation: 30453
You need to put B
in front of A
in the inheritance order for that to work:
>>> from abc import abstractmethod, ABCMeta
>>> class A:
... __metaclass__=ABCMeta
... @abstractmethod
... def a(self):
... pass
>>> class B:
... def a(self):
... return 12
>>> class C(B,A):
... pass
>>> c = C()
>>> c
<__main__.C object at 0x10e9c40d0>
>>> class D:
... pass
>>> class E(D, A):
... pass
>>> e = E()
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: Can't instantiate abstract class E with abstract methods a
Upvotes: 1