Search code examples
python-3.xpython-2.7inheritancemethodsconstructor

Issue with Inheritance in Python - Unable to Access Parent Class Method


I'm currently working on a Python project where I'm using inheritance to create a base class and a derived class. However, I'm encountering an issue when trying to access a method from the parent class within the child class.

class MyBaseClass:
def __init__(self, name):
self.name = name

    def greet(self):
        return f"Hello, {self.name}!"

class MyDerivedClass(MyBaseClass):
def __init__(self, name, age):
super().__init__(name)
self.age = age

    def display_info(self):
        # Problematic line
        greeting = self.greet()  # This results in an AttributeError
    
        return f"{greeting} I am {self.age} years old."

obj = MyDerivedClass("John", 25)
print(obj.display_info())

Issue:

The problem occurs when trying to call the greet method from the MyBaseClass within the display_info method of the MyDerivedClass. The code raises an AttributeError stating that the method does not exist.

I expected the greet method to be accessible from the child class, as it's defined in the parent class. Am I missing something in my inheritance setup, or is there a scoping issue?

What I've Tried:

  1. Ensured that the parent class (MyBaseClass) is properly initialized using super() in the child class constructor.

Solution

  • Your code is correct and you have access to your parent class methods because of the super() constructor of your parent class. But your formatting and indentation may cause this error. You can fix in this way:

    class MyBaseClass:
       def __init__(self, name):
          self.name = name
       def greet(self):
          return f"Hello, {self.name}!"
    
    class MyDerivedClass(MyBaseClass):
       def __init__(self, name, age):
          super().__init__(name)
          self.age = age
    
       def display_info(self):
          greeting = self.greet()
    
          return f"{greeting} I am {self.age} years old."
    
    obj = MyDerivedClass("John", 25)
    print(obj.display_info())