在下面的类self.num
和self.den
中,它们是在__init__
构造函数中定义的,但随后在该类中的__add__
(和其他方法)中,变量如new_num
和new_den
不是使用self定义的(也就是说,它们不是self.new_num
和self.new_den
)。是否不在__init__
构造函数之外使用self来定义变量,为什么?
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