0

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
user3124200
  • 343
  • 1
  • 5
  • 1
    `new_num` and `new_den` are just *local variables* in the method. They are there to hold intermediary values. – Martijn Pieters Jan 19 '19 at 18:50
  • 1
    `self` is just a reference to the current instance. You can access attributes on that instance, as needed. `self` is just the common name used for the first argument of bound methods, passed in automatically for any method accessed on an instance. – Martijn Pieters Jan 19 '19 at 18:51
  • Martijn could you expand on your first comment - why aren't ```new_num``` and ```new_den``` defined as ```self.new_num``` and ```self.new_den```? – user3124200 Jan 20 '19 at 06:52
  • Would you keep your back-of-the-envelope calculations when you are doing a DIY project, like putting up some shelves? Once the shelves are up on the wall, you no longer need to keep your measurements of the brackets and the planks and such, so you throw your envelope away. `new_num` and `new_den` are notes on an envelope, nothing more. You don’t keep those once you are done with the calculations. . – Martijn Pieters Jan 20 '19 at 12:50

0 Answers0