61

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 ???

3 Answers 3

63

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
Sign up to request clarification or add additional context in comments.

Comments

42

Two ways:


>>> A.print_it(x)
'A'
>>> super(B, x).print_it()
'A'

3 Comments

Is the first way passing x as the self parameter? I didn't know you could do that...
@Wilduck. Good question, do you know the answer on that one?
Yes, you pass x as the self parameter. When you use the method on an instantiated object, like x.print_it(), x is automaticaly given as the self parameter. When you use the original function from the class definition (A.print_it), A is not an instantiated object of type A, so it does not give as parameter A and expect a value for the parameter self.
2

Simple answer:

super().print_it()

1 Comment

That would work when used inside the class, but the question shows a use case outside the class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.