How to Access Child-class Methods from Parent-class in Python

This topic tells accessing child class methods from the parent class. A concept is already available to access parent class methods from child class (using the super method). Here, it is the opposite.

As part of OOPS and avoiding code repetition, you can access parent class methods from the child. Similarly, vice versa. But how? Below example explains it.

Accessing child methods from the parent

Before deep diving into details, the relationship usually goes from parent to child. Always parent is a master, and a child is born to a parent. The child can get its parent’s methods.

How to Access Child-class Methods from Parent-class in Python
Child-to-parent accessing methods in Python

Below, you will find the logic is how one can access child-class methods from the parent class. It’s also an interview question.

Child and Parent classes

Here, I have written two classes and explained how it works. And in the child class passed parent class as argument. I have now assigned the obj1 object to the parent class.

class parent:
    def __init__(self):
        pass
    def test1(self):
        print("I am in Parent")
        
class child(parent):
    def __init(self):
        pass
    def test2(self):
        print("I am in child class")
        

obj1=parent()
# Call to child-class method from parent
obj1.test2()

Output

The below result shows an error when you try to call the child method from the parent. In interviews, you can tell you would get an Attribute error. So inheritance works from parent to child and not from child to parent.

Traceback (most recent call last):
  File "main.py", line 15, in <module>
    obj1.test2()
AttributeError: 'parent' object has no attribute 'test2'


** Process exited - Return Code: 1 **
Press Enter to exit terminal

Related

Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.