Something like a virtual method in C ++ (calling the implementation of a method of a derived class through a link or a pointer to a base class) does not make sense in Python, since Python has no typing. (Although I do not know how virtual methods work in Java and PHP.)
But if by “virtual” you mean calling the lowest implementation in the inheritance hierarchy, then this is what you always get in Python, as several answers indicate.
Well, almost always ...
As dplamp pointed out, not all methods in Python behave this way. Dander method does not. And I think this is not a very famous 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
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 changed was to make prop_a() more complicated method.
The problem with the first behavior may be that you cannot change the behavior of prop_a() in a derived class without affecting the behavior of prop_b() . This very good report by Raymond Hettinger provides an example for the case when it is inconvenient.
Konstantin Dec 29 '18 at 10:16 2018-12-29 10:16
source share