python - Ensure a Method is Overridden -
i want ensure class derived class overrides methods. if not overridden want raise notimplementederror possible after compiling begins, rather when 1 of methods called.
i've found can metaclass so:
class metabaseclass(type):     # list of method names should overridden     to_override = ['method_a', 'method_b']      def __init__(cls, name, bases, dct):         methodname in cls.to_override:             if methodname not in dct:                  raise notimplementederror('{0} must override {1} method'.format(name, methodname))         super(metabaseclass, cls).__init__(name, bases, dct)  class baseclass(object):      __metaclass__ = metabaseclass      def method_a(self):         pass      def method_b(self):         pass this raise error @ class definition time if method_a or method_b aren't overridden class derived baseclass.
is there better way this?
why not use abstractmethod.
from abc import abstractmethod, abcmeta class baseclass(object):      __metaclass__ = abcmeta      @abstractmethod     def method_a(self):         pass     @abstractmethod     def method_b(self):         pass  class inherit(baseclass):     pass you error user tries instantiate inherit class.
i = inherit() typeerror: can't instantiate abstract class inherit abstract methods method_a, method_b 
Comments
Post a Comment