In the following class self.num
and self.den
are defined in the __init__
constructor, but then in the __add__
(and other methods) in the class the variables such as new_num
and new_den
are not defined using self (that is they are not self.new_num
and self.new_den
). Is self not used outside the __init__
constructor to define variables and why?
class Fraction:
def __init__(self, top, bottom):
self.num = top
self.den = bottom
def __str__(self):
return str(self.num) + "/" + str(self.den)
def show(self):
print(self.num, "/", self.den)
def __add__(self, other_fraction):
new_num = self.num * other_fraction.den + \
self.den * other_fraction.num
new_den = self.den * other_fraction.den
common = gcd(new_num, new_den)
return Fraction(new_num // common, new_den // common)
def __eq__(self, other):
first_num = self.num * other.den
second_num = other.num * self.den
return first_num == second_num