oop - Python base class that makes abstract methods definition mandatory at instantiation -


i have base class define couple of empty methods. enforce/make mandatory definition of these methods in subclass , make crash @ init in case not overriden.

ex:

class shape:     def __init__(self, name):         self.name = name     def number_of_edges(self):         pass  # method has overloaded in subclass  class triangle(shape):     def __init__(self, name):         super(triangle, self).__init__()      def number_of_edges(self):         return 3 

it seems python way raise notimplementederror:

def number_of_edges(self):     raise(notimplementederror) 

but beneficial crash , detect lack of implementation during class instantiation. why not default, , can done?

use abc module create abstract base class.

import abc  class shape(object):     __metaclass__ = abc.abcmeta      def __init__(self, name):         self.name = name      @abc.abstractmethod     def number_of_edges(self):         pass 

any method decorated @abc.abstractmethod decorator trigger typeerror exception:

>>> import abc >>> class shape(object): ...     __metaclass__ = abc.abcmeta ...     def __init__(self, name): ...         self.name = name ...     @abc.abstractmethod ...     def number_of_edges(self): ...         pass ... >>>   >>> class triangle(shape): ...     pass ...  >>> triangle('t3') traceback (most recent call last):   file "<stdin>", line 1, in <module> typeerror: can't instantiate abstract class triangle abstract methods number_of_edges >>> class triangle(shape): ...     def number_of_edges(self): ...         return 3 ...  >>> triangle('t3') <__main__.triangle object @ 0x105f3b8d0> 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -