In Python, how do you make 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.
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.
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.
# 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__()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With