Calling base class method in Python

PythonClass

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

Two ways:


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

Solution 3 - Python

Simple answer:

super().print_it()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser225312View Question on Stackoverflow
Solution 1 - Pythonuser225312View Answer on Stackoverflow
Solution 2 - PythonprimrootView Answer on Stackoverflow
Solution 3 - PythonbonkeyView Answer on Stackoverflow