python @abstractmethod decorator

前端 未结 1 2177
南旧
南旧 2021-01-31 02:21

I have read python docs about abstract base classes:

From here:

abc.abstractmethod(function) A decorator indicating abstract method

相关标签:
1条回答
  • 2021-01-31 02:44

    Are you using python3 to run that code? If yes, you should know that declaring metaclass in python3 have changes you should do it like this instead:

    import abc
    
    class AbstractClass(metaclass=abc.ABCMeta):
    
      @abc.abstractmethod
      def abstractMethod(self):
          return
    

    The full code and the explanation behind the answer is:

    import abc
    
    class AbstractClass(metaclass=abc.ABCMeta):
    
        @abc.abstractmethod
        def abstractMethod(self):
            return
    
    class ConcreteClass(AbstractClass):
    
        def __init__(self):
            self.me = "me"
    
    # Will get a TypeError without the following two lines:
    #   def abstractMethod(self):
    #       return 0
    
    c = ConcreteClass()
    c.abstractMethod()
    

    If abstractMethod is not defined for ConcreteClass, the following exception will be raised when running the above code: TypeError: Can't instantiate abstract class ConcreteClass with abstract methods abstractMethod

    0 讨论(0)
提交回复
热议问题