Pallab Ganguly
Pallab Ganguly

Reputation: 3183

How can I resolve this 'has no attribute' error in Python?

I tried to make a class Parent and a subclass called Child. After that I passed the arguments of child to parent using the constructor init but this error keeps getting thrown. How can I fix this? By the way if I assign the values in the subclass by doing Parent.name=name, etc it works fine. But how can I do this using a constructor?

class Parent(object):
    def __init__(self, name, color):
        print("Parent Constructor called")
        self.firstname=name
        self.eyecolor=color

class Child(Parent):
    def __init__(self, name, color, toys):
        print("Child Constructor called")
        Parent.__init__(self,name,color)
        self.toys=toys

robert_langdon=Child("Holmes", "brown", 5)
print(robert_langdon.name)
print(robert_langdon.toys)

Snapshot of the error thrown

Upvotes: 1

Views: 644

Answers (1)

Angus Williams
Angus Williams

Reputation: 2334

I belive this should work (I've used super so as not to refer to the base class explicitly, and you were also looking for the wrong attribute (should be firstname not name)):

class Parent(object):
    def __init__(self, name, color):
        print("Parent Constructor called")
        self.firstname=name
        self.eyecolor=color

class Child(Parent):
    def __init__(self, name, color, toys):
        print("Child constructor called")
        super(Child,self).__init__(name,color)
        self.toys=toys

robert_langdon=Child("Holmes", "brown", 5)
print(robert_langdon.firstname)
print(robert_langdon.toys)

Upvotes: 1

Related Questions