I have two classes A and B and A is base class of B.
I read that all methods in Python are virtual.
So how do I call a method of the base because when I try to call it, the method of the derived class is called as expected?
>>> class A(object): def print_it(self): print 'A' >>> class B(A): def print_it(self): print 'B' >>> x = B() >>> x.print_it() B >>> x.A ???
Static method can be called without creating an object or instance. Simply create the method and call it directly. This is in a sense orthogonal to object orientated programming: we call a method without creating objects.
Python provides a __bases__ attribute on each class that can be used to obtain a list of classes the given class inherits. The __bases__ property of the class contains a list of all the base classes that the given class inherits.
Using super:
>>> class A(object): ... def print_it(self): ... print 'A' ... >>> class B(A): ... def print_it(self): ... print 'B' ... >>> x = B() >>> x.print_it() # calls derived class method as expected B >>> super(B, x).print_it() # calls base class method A
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With