oop - Is it possible in Python to declare that method must be overridden? -
i have "abstract" class, such as:
class a:     def do_some_cool_stuff():         ''' 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 way declare, method a.do_some_cool_stuff must overriden, and, possibly warning should raised while trying create b-class object, when b had not implemented a.do_some_cool_stuff?
yes, defining a abc (abstract base class):
from abc import abcmeta, abstractmethod  class a(object):     __metaclass__ = abcmeta      @abstractmethod     def do_some_cool_stuff():         ''' override '''         pass      def do_some_boring_stuff():         return 2 + 2   you can subclass a, can create instances of such subclass if do_some_cool_stuff() method has concrete implementation:
>>> abc import abcmeta, abstractmethod >>> class a(object): ...     __metaclass__ = abcmeta ...     @abstractmethod ...     def do_some_cool_stuff(): ...         ''' 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 abstract methods do_some_cool_stuff      
Comments
Post a Comment