Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How do I make a subclass from a superclass?

Tags:

python

class

In Python, how do you make a subclass from a superclass?

like image 950
dave.j.lott Avatar asked Oct 22 '09 14:10

dave.j.lott


People also ask

How do you define a subclass from a superclass?

Definition: A subclass is a class that derives from another class. A subclass inherits state and behavior from all of its ancestors. The term superclass refers to a class's direct ancestor as well as all of its ascendant classes.

How do you create a subclass in Python?

The process of creating a subclass of a class is called inheritance. All the attributes and methods of superclass are inherited by its subclass also. This means that an object of a subclass can access all the attributes and methods of the superclass.

How do you get the 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.


1 Answers

# Initialize using Parent # class MySubClass(MySuperClass):     def __init__(self):         MySuperClass.__init__(self) 

Or, even better, the use of Python's built-in function, super() (see the Python 2/Python 3 documentation for it) may be a slightly better method of calling the parent for initialization:

# Better initialize using Parent (less redundant). # class MySubClassBetter(MySuperClass):     def __init__(self):         super(MySubClassBetter, self).__init__() 

Or, same exact thing as just above, except using the zero argument form of super(), which only works inside a class definition:

class MySubClassBetter(MySuperClass):     def __init__(self):         super().__init__() 
like image 157
thompsongunner Avatar answered Sep 22 '22 14:09

thompsongunner