1

I am getting an AttributeError when I am trying to inherit an attribute from parent's class function. Does this mean that I can't inherit it directly from parent's function? This is the output:

AttributeError: 'Two' object has no attribute 'name'

and this is the code itself:

This is the code:

class One:
def ready(self):
    self.name = 'John'

class Two(One):
def __init__(self):
    print(self.name)

two = Two()

2 Answers 2

2

In an instance of the class One the attribute name is only set when self.ready() is called. When you try to print it in Two.__init__ it is not added yet and therefore raises an error. So you would need to use something like:

class One:
  def ready(self):
    self.name = 'John'

class Two(One):
  def __init__(self):
    self.ready()
    print(self.name)

two = Two()
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. What instead of def ready(self) I had __init__(self) in place?
__init__ of the parent class is not called by default so you would have to call super().__init__()
-1

You're getting an attribute error because you're not defining any self.name in class Two. Even though, two is inheriting from One the class instances are different. You could instead try

   class Two(One):
     def __init__(self):
         One.ready(self)
         print(self.name)

Try searching what is self, inheritance and constructors in python if you want to get a better idea.

1 Comment

You really should use self.ready, I didn't downvote, btw, but I think people will not like that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.