Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible in Python to declare that method must be overridden?

Tags:

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?

like image 368
utter_step Avatar asked Jul 01 '13 10:07

utter_step


Video Answer


1 Answers

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 
like image 125
Martijn Pieters Avatar answered Oct 02 '22 13:10

Martijn Pieters