self是否用于在构造函数init方法之外的类中定义变量?

时间:2019-01-19 18:48:54

标签: python python-3.x

在下面的类self.numself.den中,它们是在__init__构造函数中定义的,但随后在该类中的__add__(和其他方法)中,变量如new_numnew_den不是使用self定义的(也就是说,它们不是self.new_numself.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

0 个答案:

没有答案