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
CodePudding user response:
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()
CodePudding user response:
There seems to be a problem with the "init" spelling. not "init" has to __init__
and you have to give some thing to introduce_self
because function outside the class. And the code should look like this :
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)
introduce_self(r2)
>>>my name is Jerry
You can also enclose your function in class and do it:
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()
>>>my name is Jerry