54

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 ???
user225312
  • 126,773
  • 69
  • 172
  • 181

3 Answers3

57

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
user225312
  • 126,773
  • 69
  • 172
  • 181
40

Two ways:


>>> A.print_it(x)
'A'
>>> super(B, x).print_it()
'A'
primroot
  • 1,686
  • 1
  • 15
  • 17
  • 2
    Is the first way passing `x` as the self parameter? I didn't know you could do that... – Wilduck Jan 20 '11 at 15:47
  • @Wilduck. Good question, do you know the answer on that one? – magu_ Mar 23 '14 at 08:30
  • 2
    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`. – FunkySayu Aug 13 '15 at 13:39
0

Simple answer:

super().print_it()
cigien
  • 57,834
  • 11
  • 73
  • 112
bonkey
  • 11
  • That would work when used inside the class, but the question shows a use case outside the class. – joanis Dec 14 '21 at 20:11