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
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()