I’m still getting my head around classes in Python,
class Triangle(object):
def __init__(self, angle1, angle2, angle3):
angle1 = self.angle1
angle2 = self.angle2
angle3 = self.angle3
number_of_sides = 3
def check_angles(angle1, angle2, angle3):
if angle1+angle2+angle3 == 180:
return True
else:
return False
my_triangle = Triangle(30, 60, 90)
print(Triangle.number_of_sides)
print(Triangle.check_angles)
So what’s wrong?
Stackoverflow has some really mean users, I come from MathStackExchange and people didn’t downvote novice/noob questions as much as they do here.
You have your assignments backward:
etc.
Thinking about what is going on a little bit might help here.
selfis an instance of the classTrianglethat is passed in. So,Within
method_call,selfis a reference toT. (__init__is kind of magic — It gets called automatically on the first line, but the principle is still the same). Once you know that, it’s easy to see why you needself.whatever = whatever— You’re putting a new attribute on the objectT!Finally, this explains how you should write
check_angles:Now a quick diversion into class attributes. You can put attributes onto a class as well:
I think it is customary to define class attributes before you define your methods (functions), but you don’t actually have to. (It will help the readers of your code understand it though — I misunderstood your original code because of the order you did things).
You can dynamically add attributes to a class after the class has been created as well:
You can get access to
Triangle.some_attributea few ways. The first way is directly through the class (Triangle.number_of_sides). The second way is via an instance:This seems a little funny at first. After all, the instance doesn’t have a
number_of_sidesattribute. It turns out that python is designed to look at the instance first to see if it has it’s ownnumber_of_sidesattribute. If it does, great, that’s what you get. If it doesn’t however, python will then look at the class for the attribute. This turns into a handy way to share data between instances of a class.