Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling base class method in Python

Tags:

python

class

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 ??? 
like image 365
user225312 Avatar asked Jan 20 '11 12:01

user225312


People also ask

Can you call the base class method without creating an instance in Python?

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.

What is __ base __ in Python?

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.


1 Answers

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 
like image 54
user225312 Avatar answered Sep 28 '22 19:09

user225312