Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call subclass methods in a superclass in Python

Tags:

python

I want to know how to call subclass methods in the superclass.

like image 361
zta1987 Avatar asked Feb 03 '12 08:02

zta1987


People also ask

Can we call subclass method using superclass object Python?

Yes, you can call the methods of the superclass from static methods of the subclass (using the object of subclass or the object of the superclass).

How do you call subclass method from superclass?

Yes its possible to call sub class methods using super class by type casting to sub class object . By type casting super class object to sub class object we can access all corresponding sub class and all super class methods on that reference.

How do you call a subclass in Python?

Python super() Function __init__ , we can use the super() function for calling the constructor and methods of the parent class inside the child class. The super() function returns a parent class object and can be used to access the attributes or methods of the parent class inside the child class.

Can a subclass be a superclass Python?

The class from which a class inherits is called the parent or superclass. A class which inherits from a superclass is called a subclass, also called heir class or child class. Superclasses are sometimes called ancestors as well. There exists a hierarchical relationship between classes.


2 Answers

I believe this is a pattern used often.

class A(object):
    def x(self):
        self.y()

    def y(self):
        print('default behavior')


class B(A):
    def y(self):
        print('Child B behavior')

class C(A):
    def z(self):
        pass

>>>B().x()
Child B behavior
>>>C().x()
default behavior

It is sort of like an abstract class, but provides default behavior. Can't remember the name of the pattern off the top of my head though.

like image 85
zer0mind Avatar answered Sep 18 '22 19:09

zer0mind


Here's what I've just tried:

class A(object):
    def x(self): 
        print self.y()

class B(A):
    def y(self): 
        return 1

>>> B().x()
1

So unless you had some specific problem, just call a method from the subclass in the base class and it should just work.

like image 45
Tomasz Zieliński Avatar answered Sep 22 '22 19:09

Tomasz Zieliński