How to implement virtual methods in Python?

前端 未结 6 1029
自闭症患者
自闭症患者 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:24

    Something like a virtual method in C++ (calling method implementation of a derived class through a reference or pointer to the base class) doesn't make sense in Python, as Python doesn't have typing. (I don't know how virtual methods work in Java and PHP though.)

    But if by "virtual" you mean calling the bottom-most implementation in the inheritance hierarchy, then that's what you always get in Python, as several answers point out.

    Well, almost always...

    As dplamp pointed out, not all methods in Python behave like that. Dunder method don't. And I think that's a not so well known feature.

    Consider this artificial example

    class A:
        def prop_a(self):
            return 1
        def prop_b(self):
            return 10 * self.prop_a()
    
    class B(A):
        def prop_a(self):
            return 2
    

    Now

    >>> B().prop_b()
    20
    >>> A().prob_b()
    10
    

    However, consider this one

    class A:
        def __prop_a(self):
            return 1
        def prop_b(self):
            return 10 * self.__prop_a()
    
    class B(A):
        def __prop_a(self):
            return 2
    

    Now

    >>> B().prop_b()
    10
    >>> A().prob_b()
    10
    

    The only thing we've changes was making prop_a() a dunder method.

    A problem with the first behavior can be that you can't change the behavior of prop_a() in the derived class without impacting the behavior of prop_b(). This very nice talk by Raymond Hettinger gives an example for a use case where this is inconvenient.

提交回复
热议问题