A slightly bigger example, tying classes, dunder methods, and a bit of number theory together —
a Fraction class that supports +, ==, and eventually *, -, and /.
class Fraction: def __init__(self, top, bottom): self.num = top self.den = bottom
def __str__(self): return str(self.num) + "/" + str(self.den)
'''Now to add another fraction, we have to make sure they have a common denominator to do that. The best way to do that is to simply use the product of both fraction's denominators as the common denominator. so a/b + c/d will be ad/bd + cb/bd which will be equal to ad+cb/bd. This is what we have implemented in the __add__ method below'''
def __add__(self, otherfraction): newnum = self.num * otherfraction.den + self.den * otherfraction.num newden = self.den * otherfraction.den '''the below is just a way to get the greatest common divisor for each , in order to get the reduced version of the fraction when we add them''' common = gcd(newnum, newden) return Fraction(newnum // common, newden // common)
def __eq__(self, other): firstnum = self.num * other.den secondnum = other.num * self.den return firstnum == secondnum
def gcd(m, n): while m % n != 0: oldm = m oldn = n m = oldn n = oldm % oldn return n
x = Fraction(1, 2)y = Fraction(2, 3)print(x + y)print(x == y)Walking through it:
- Class definition —
Fractionrepresents a fraction, with methods to perform operations on it. - Constructor (
__init__) — initializes aFractionwithtop(numerator) andbottom(denominator), assigned tonumandden. - String representation (
__str__) — returns a string in the form"numerator/denominator". - Addition (
__add__) — overrides+forFractionobjects. It computes the sum of two fractions by finding a common denominator, adding the numerators, and then reducing the resulting fraction to its simplest form. - Equality comparison (
__eq__) — overrides==forFractionobjects, comparing two fractions by cross-multiplying and comparing the results. - Greatest common divisor (
gcd) — calculates the GCD of two integers using Euclid’s algorithm, used to reduce fractions to their simplest form.
This implementation demonstrates the creation of Fraction objects, addition of fractions, and
comparison of fractions for equality, all while ensuring the fractions are in their simplest form.
This is how the multiplication, division, and subtraction methods would be implemented:
def __mul__(self, other): newnum = self.num * other.num newden = self.den * other.den common = gcd(newnum, newden) return Fraction(newnum // common, newden // common)
def __sub__(self, otherfraction): newnum = self.num * otherfraction.den - self.den * otherfraction.num newden = self.den * otherfraction.den common = gcd(newnum, newden) return Fraction(newnum // common, newden // common)
def __truediv__(self, otherfraction): newnum = self.num * otherfraction.den newden = self.den * otherfraction.num common = gcd(newnum, newden) return Fraction(newnum // common, newden // common)