How to implement virtual methods in Python?

前端 未结 6 1005
自闭症患者
自闭症患者 2020-12-04 11:41

I know virtual methods from PHP or Java.

How can they be implemented in Python?

Or have I to define an empty method in an abstract class and override it?

6条回答
  •  离开以前
    2020-12-04 12:37

    raise NotImplementedError()

    This is the recommended exception to raise on "pure virtual methods" of "abstract" base classes that don't implement a method.

    https://docs.python.org/3.5/library/exceptions.html#NotImplementedError says:

    This exception is derived from RuntimeError. In user defined base classes, abstract methods should raise this exception when they require derived classes to override the method.

    As others said, this is mostly a documentation convention and is not required, but this way you get a more meaningful exception than a missing attribute error.

    E.g.:

    class Base(object):
        def virtualMethod(self):
            raise NotImplementedError()
        def usesVirtualMethod(self):
            return self.virtualMethod() + 1
    
    class Derived(Base):
        def virtualMethod(self):
            return 1
    
    print Derived().usesVirtualMethod()
    Base().usesVirtualMethod()
    

    gives:

    2
    Traceback (most recent call last):
      File "./a.py", line 13, in 
        Base().usesVirtualMethod()
      File "./a.py", line 6, in usesVirtualMethod
        return self.virtualMethod() + 1
      File "./a.py", line 4, in virtualMethod
        raise NotImplementedError()
    NotImplementedError
    

    Related: Is it possible to make abstract classes in Python?

提交回复
热议问题