I have an "abstract" class, such as:
class A: def do_some_cool_stuff(): ''' To override ''' pass def do_some_boring_stuff(): return 2 + 2
And class B, subclassing A:
class B(A): def do_stuff() return 4
Is there any way to declare, that a method A.do_some_cool_stuff
must be overriden, and, possibly that some warning should be raised while trying to create B-class object, when B had not implemented A.do_some_cool_stuff
?
Yes, by defining A
as an ABC (Abstract Base Class):
from abc import ABCMeta, abstractmethod class A(object): __metaclass__ = ABCMeta @abstractmethod def do_some_cool_stuff(): ''' To override ''' pass def do_some_boring_stuff(): return 2 + 2
You can subclass A
, but you can only create instances of such a subclass if the do_some_cool_stuff()
method has a concrete implementation:
>>> from abc import ABCMeta, abstractmethod >>> class A(object): ... __metaclass__ = ABCMeta ... @abstractmethod ... def do_some_cool_stuff(): ... ''' To override ''' ... pass ... def do_some_boring_stuff(): ... return 2 + 2 ... >>> class B(A): ... def do_stuff(): ... return 4 ... >>> B() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Can't instantiate abstract class B with abstract methods do_some_cool_stuff
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With