Error is:
Equilateral object has no attribute angle1.
please suggest how to fix this error and also please explain how self works. I am confused where to use self and where to not
class Triangle(object):
number_of_sides=3
def __init__(self,angle1,angle2,angle3):
self.angle1=angle1
self.angle2=angle2
self.angle3=angle3
def check_angles(self):
if self.angle1+self.angle2+self.angle3==180:
return True
else:
return False
class Equilateral(Triangle): //inheritance
angle=60
def __init__(self):
self.angle=self.angle1
self.angle=self.angle2
self.angle=self.angle3
man=Equilateral()
man.check_angles()
3 Answers 3
You have it the wrong way around
self.angle1= self.angle
etc
Self refers to the instantiated object, much like 'this' in java. You attach attributes to the object using this keyword.
When defining variables on an object, attributes at the beginning of your class definition do not need self- they are class attributes which all instances of the object will create on instantiation, whereas variables you change or set using self are instance variables and not found on all instances of the object.
1 Comment
Different from other languages, Python does not call __init__() of the super class. You have to call it yourself:
class Equilateral(Triangle):
angle=60
def __init__(self, ...):
super().__init__(...)
self.angle=self.angle1
More details
Comments
You have to call __init__ from the super class:
class Triangle(object):
number_of_sides=3
def __init__(self,angle1,angle2,angle3):
self.angle1=angle1
self.angle2=angle2
self.angle3=angle3
def check_angles(self):
return self.angle1+self.angle2+self.angle3==180:
class Equilateral(Triangle):
angle=60
def __init__(self):
Triangle.__init__(self, self.angle, self.angle, self.angle)
man=Equilateral()
man.check_angles()
6 Comments
super(Equilateral, self).__init__(...)
#, not//.