Python's super(), abstract base classes, and NotImplementedError

前端 未结 3 1616
慢半拍i
慢半拍i 2021-02-03 14:45

Abstract base classes can still be handy in Python. In writing an abstract base class where I want every subclass to have, say, a spam() method, I want to write som

3条回答
  •  再見小時候
    2021-02-03 15:15

    You can do this cleanly in python 2.6+ with the abc module:

    import abc
    class B(object):
        __metaclass__ = abc.ABCMeta
        @abc.abstractmethod
        def foo(self):
            print 'In B'
    
    class C(B):
        def foo(self):
            super(C, self).foo()
            print 'In C'
    
    C().foo()
    

    The output will be

    In B
    In C
    

提交回复
热议问题