I want to know how to call subclass methods in the superclass.
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).
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.
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.
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.
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.
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.
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