0
Class Methods
Trying to get a program to print the perimeter of a triangle. I borrowed from the class methods module to practice and added/changed as needed. Says error in line 13 is "undefined" but I cannot figure out why? Any ideas? class triangle: def __init__(self, left, right, bottom): self_left = left self_right = right self_bottom = bottom def calculate_perimeter(self): return self_left + self_right + self_bottom @classmethod def new_tri(cls, perimeter): return cls(self_left + self_right + self_bottom) perimeter = triangle.new_tri(5) print(perimeter.calculate_perimeter())
1 Resposta
+ 1
You need to define the attributes of an instance with self._left.
If you leave out the dot, self_left is just a regular variable and will be deleted after the end of init.
Also you need to understand that a class method doesn't know 'self' because a class method gets the *class* as first argument, not 'self'.
From what I see, I'd recommend to practice with regular methods in simple cases a bit more, since there are still deficits. Do class methods after you firmly understood the basics of how classes work.