Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

AttributeError: 'Robot' object has no attribute 'introduce_self'

I’m a beginner in class & objects and was wondering why the line r2.introduce_self had an attribute error with an object that doesn’t have an attribute.

class Robot:
    def __init__(self, rname, rcolor, rweight):
        self.name = rname
        self.color = rcolor
        self.weight = rweight


def introduce_self(self):
    print("my name is " + self.name)


r1 = Robot("Tom", "Red", 30)
r2 = Robot("Jerry", "Blue", 40)

r2.introduce_self()

I tried to check if there were any indentation errors but they were all fine, the code is supposed to have an output that says "my name is Jerry". But it still had an attribute error unfortunately

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I believe it is because your indentation having issue. introduce_self should be a method for Robot, so it should be having the same indent as __init__ of Robot class.

Try the below code

class Robot:
    def __init__(self, rname, rcolor, rweight):
        self.name = rname
        self.color = rcolor
        self.weight = rweight
    
    def introduce_self(self):
        print("my name is " + self.name)


r1 = Robot("Tom", "Red", 30)
r2 = Robot("Jerry", "Blue", 40)

r2.introduce_self()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading