First Summer 2006


Lab Thirteen: Designing Objects.
Let's develop a Fraction class:

class Fraction(object):
    def __init__(self, num, den):
        self.num = num
        self.den = den

Here's how it behaves so far:

>>> f = Fraction(2, 3)
>>> f.num
2
>>> f.den
3
>>> f.num = 5
>>> f.num
5
>>> f.den
3
>>>

Let's add a reporting function:

class Fraction(object):
    def __init__(self, num, den):
        self.num = num
        self.den = den
    def show(self):
        return str(self.num) + "/" + str(self.den)

This simplifies a bit the interaction:

>>> a = Fraction(1,2)
>>> a.show()
'1/2'
>>> a
<__main__.Fraction object at 0xb7b94e2c>
>>> a.num = 3
>>> a.show()
'3/2'
>>> a
<__main__.Fraction object at 0xb7b94e2c>
>>>

Now we can teach the Fractions addition:

class Fraction(object):
    def __init__(self,num,den):
        self.n = num
        self.d = den
    def report(self):
        return str(self.n) + "/" + str(self.d)
    def add(self,f):
        return Fraction(self.n*f.d+self.d*f.n,self.d*f.d)

This is almost good, but sometimes not in lowest terms:

>>> a = Fraction(1,2)
>>> b = Fraction(1,3)
>>> a.add(b)
<__main__.Fraction object at 0xb7b9b02c>
>>> c = a.add(b)
>>> c.show()
'5/6'
>>> a = Fraction(1,2)
>>> b = a.add(a)
>>> b.show()
'4/4'
>>>

Let's add a (static) gcd method, to make sure all fractions are in lowest terms:

class Fraction(object):
    def __init__(self, num, den):
        self.num = num/Fraction.gcd(num, den)
        self.den = den/Fraction.gcd(num, den)
        print self.show(), "has been created."
    def show(self):
        return str(self.num) + "/" + str(self.den)
    def add(self, other):
        return Fraction(self.num * other.den + self.den * other.num, self.den * other.den)
    def gcd(n, m):
        for val in range(min(n, m), 1, -1):
            if n % val == 0 and m % val == 0:
                return val
        return 1
    gcd = staticmethod(gcd)

So now here's a typical session:

>>> a = Fraction(1, 2)
1/2 has been created.
>>> a
<__main__.Fraction object at 0xb7b9bbac>
>>> a.show()
'1/2'
>>> b = Fraction(6, 18)
1/3 has been created.
>>> b
<__main__.Fraction object at 0xb7b9b34c>
>>> a.add(Fraction(3,2))
3/2 has been created.
2/1 has been created.
<__main__.Fraction object at 0xb7b9b7ac>
>>> c = a.add(Fraction(3,2))
3/2 has been created.
2/1 has been created.
>>> c.show()
'2/1'
>>> (a.add(a)).show()
1/1 has been created.
'1/1'
>>>

Can you explain, do you understand the interaction we have presented above?


Last updated: June 6, 2006 by Adrian German for A201/A597