How define constructor implementation for an Abstract Class in Python?

前端 未结 5 1149
难免孤独
难免孤独 2020-12-29 01:32

I am trying to declare an abstract class A with a constructor with a default behavior: all subclasses must initialize a member self.n:



        
5条回答
  •  死守一世寂寞
    2020-12-29 02:01

    Making the __init__ an abstract method:

    from abc import ABCMeta, abstractmethod
    
    class A(object):
        __metaclass__ = ABCMeta
    
        @abstractmethod
        def __init__(self, n):
            self.n = n
    
    
    if __name__ == '__main__':
        a = A(3)
    

    helps:

    TypeError: Can't instantiate abstract class A with abstract methods __init__
    

    Python 3 version:

    from abc import ABCMeta, abstractmethod
    
    class A(object, metaclass=ABCMeta):
    
        @abstractmethod
        def __init__(self, n):
            self.n = n
    
    
    if __name__ == '__main__':
        a = A(3)
    

    Works as well:

    TypeError: Can't instantiate abstract class A with abstract methods __init__
    

提交回复
热议问题