Writing a Fraction Class
• Sofarwehaveworkedwithfloa0ng-pointnumbersbutcomputers
storebinaryvalues,sonotallrealnumberscanberepresented
precisely
• Inapplica0onswheretheprecisionofrealnumbersisimportant,we
canusera#onalnumberstostoreexactvalues
• Thishelpstoreduceoreliminateround-offerrorsthatcanoccur
whenperformingarithme0copera0ons
• Ara0onalnumberisanumberthatcanbeexpressedasara0oof
twointegers:7/8
• ThetopvalueiscalledthenumeratorandtheboFomvalue,which
cannotbezero,iscalledthedenominator
11/4/16
83
Designing the Fraction Class
• Wewanttouseourra0onalnumbersaswewoulduseintegersand
floa0ngpointvalues
• Thus,ourFractionclassmustperformthefollowingopera0ons:
1. Createara0onalnumber
2. Accessthenumeratoranddenominatorvalues,individually
3. Determineifthera0onalnumberisnega0veorzero
4. Performnormalmathema0calopera0onsontwora0onal
numbers(addi0on,subtrac0on,mul0plica0on,division,
exponen0a0on)
5. Logicallycomparetwora0onalnumbers
6. Produceastringrepresenta0onofthera0onalnumber
• TheobjectsoftheFrac0onclasswillbeimmutablebecausenoneof
theopera0onsmodifytheobjects’instancevariables
11/4/16
84
Required Data Attributes
• Becauseara0onalnumberconsistsoftwointegers,weneedtwo
instancevariablestostorethosevalues:
self._numerator=0
self._denominator=1
• Atno0meshouldthera0onalnumberbeconvertedtoafloa0ng-point
valueorwewilllosetheprecisiongainedfromworkingwithra0onal
numbers
11/4/16
85
Representing Values Equivalently
• Signedvalues
• Nega0veandposi0vera0onalnumberseachhavetwoformsthat
canbeusedtospecifythecorrespondingvalue
• Posi0vevaluescanbeindicatedas1/2 or –1/–2,andnega0vevalues
as–2/5 or 2/–5
• Whenperforminganarithme0copera0onorlogicallycomparing
twora0onalnumbers,itwillbemucheasierifwehaveasingleway
torepresentanega0vevalue
• Forsimplicity,wechoosetosetonlythenumeratortoanega0ve
valuewhenthera0onalnumberisnega0ve,andboththenumerator
anddenominatorwillbeposi0veintegerswhenthera0onalnumber
isposi0ve
11/4/16
86
Representing Values Equivalently
• Equivalentfrac0ons
• Forexample,1/4canbewriFenas1/4,2/8,16/64,or123/492
• Itwillbemucheasiertoperformtheopera0onifthenumberis
storedinreducedform
11/4/16
87
The Constructor (1)
• BecauseFractionobjectsareimmutable,theirvaluesmustbeset
whentheyarecreated.Thisrequiresparametervariablesforboththe
numeratoranddenominator
def__init__(self,numerator,denominator):
• Themethodmustcheckforspecialcases:
• Zerodenominators
• Thenumberrepresentszerooranega0venumber
11/4/16
88
The Constructor
def__init__(self,numerator=0,denominator=1):
ifdenominator==0:
raiseZeroDivisionError("Denominatorcannotbezero.")
ifnumerator==0:
self._numerator=0
self._denominator=1
else:
if(numerator<0anddenominator>=0or
numerator>=0anddenominator<0):
sign=-1
else:
sign=1
11/4/16
89
The Constructor
a=abs(numerator)
b=abs(denominator)
whilea%b!=0:
tempA=a
tempB=b
a=tempB
b=tempA%tempB
self._numerator=abs(numerator)#b*sign
self._denominator=abs(denominator)#b
11/4/16
90
Testing the Constructor
frac1=Fraction(1,8)#Storedas1/8
frac2=Fraction(-2,-4)#Storedas1/2
frac3=Fraction(-2,4)#Storedas-1/2
frac4=Fraction(3,-7)#Storedas-3/7
frac5=Fraction(0,15)#Storedas0/1
frac6=Fraction(8,0)#Error!exceptionisraised.
11/4/16
91
Comparing Fractions (1)
• InPython,wecandefineandimplementmethodsthatwillbecalled
automa0callywhenastandardPythonoperator(+,*,==,<)isapplied
toaninstanceoftheclass
• Forexample,totestwhethertwofrac0onsareequal,wecould
implementamethod:
• isequal()anduseitasfollows:
iffrac1.isequal(frac2):
print("Thefractionsareequal.")
11/4/16
92
Comparing Fractions (2)
• Ofcourse,wewouldprefertousetheoperator==
• Thisisachievedbydefiningthespecialmethod:
__eq__():
def__eq__(self,rhsValue):
return(self._numerator==rhsValue.numeratorand
self._denominator==rhsValue.denominator)
• Automa0callycallsthismethodwhenwecomparetwoFraction
objectsusingthe==operator:
iffrac1==frac2:#Callsfrac1.__eq__(frac2)
print("Thefractionsareequal.")
11/4/16
93
Special Methods
• Somespecialmethodsarecalledwhenaninstanceoftheclassis
passedtoabuilt-infunc0on.Forexample,supposeyouaFemptto
convertaFractionobjecttoafloa0ngpointnumberusingthe
float()func0on:
x=float(frac1)
• Thenthe__float__()specialmethodiscalled.
• Hereisadefini0onofthatmethod:
def__float__(self):
returnself._numerator/self._denominator
11/4/16
94
Common Special Methods
11/4/16
95
Common Special Methods
11/4/16
96
Addition of Fractions
• Allofthearithme0copera0onsthatcanbeperformedonaFraction
objectshouldreturntheresultinanewFractionobject
• Forexample,whenthestatementbelowisexecuted,frac1shouldbe
addedtofrac2andtheresultreturnedasanewFractionobjectthat
isassignedtothenewFracvariable
newFrac=frac1+frac2
11/4/16
97
Fractional Addition
• Fromelementaryarithme0c,youknowthattwofrac0onsmusthavea
commondenominatorinordertoaddthem.Iftheydonothavea
commondenominator,wecans0lladdthemusingtheformula:
11/4/16
98
Defining the Method For Addition
def__add__(self,rhsValue):
num=(self._numerator*rhsValue._denominator+
self._denominator*rhsValue._numerator)
den=self._denominator*rhsValue._denominator
returnFraction(num,den)
11/4/16
99
Logic: Less Than
• Notethata / b < c / dwhend · a < b · c.(Mul0plybothsideswithb ·
d.)
• Basedonthisobserva0on,thelessthanopera0onisimplementedby
the__lt__()methodasfollows:
def__lt__(self,rhsValue):
return(self._numerator*rhsValue._denominator
self._denominator*rhsValue._numerator)
11/4/16
100
Fraction.py
11/4/16
101
Fraction.py
11/4/16
102
Fraction.py
11/4/16
103
Fraction.py
11/4/16
104
Checking Type
• Toensurethatvariablesarethecorrecttype,Pythonprovidesthe
built-inisinstance()func0onthatcanbeusedtocheckthetypeof
objectreferencedbyavariable.
• Forexample,theconstructorfortheFractionclassrequirestwo
integers
classFraction:
def__init__(self,numerator,denominator):
if(notisinstance(numerator,int)or
notisinstance(denominator,int)):
raiseTypeError
("Thenumeratoranddenominatormustbeintegers.")
11/4/16
105
Summary: Classes and Objects
• Aclassdescribesasetofobjectswiththesamebehavior
• Everyclasshasapublicinterface:acollec0onofmethodsthrough
whichtheobjectsoftheclasscanbemanipulated
• Encapsula0onistheactofprovidingapublicinterfaceandhiding
theimplementa0ondetails
• Encapsula0onenableschangesintheimplementa0onwithout
affec0ngusersofaclass
11/4/16
106
Summary: Variables and Methods
• Anobject’sinstancevariablesstorethedatarequiredforexecu0ngits
methods
• Eachobjectofaclasshasitsownsetofinstancevariables
• Aninstancemethodcanaccesstheinstancevariablesoftheobjecton
whichitacts
• Aprivateinstancevariableshouldonlybeaccessedbythemethodsof
itsownclass
• Classvariableshaveasinglecopyofthevariablesharedamongallof
theinstancesoftheclass
11/4/16
107
Summary: Method Headers, Data
• MethodHeaders
• Youcanusemethodheadersandmethodcommentstospecifythe
publicinterfaceofaclass
• Amutatormethodchangestheobjectonwhichitoperates
• Anaccessormethoddoesnotchangetheobjectonwhichit
operates
• DataRepresenta0on
• Foreachaccessormethod,anobjectmusteitherstoreorcompute
theresult
• Commonly,thereismorethanonewayofrepresen0ngthedataof
anobject,andyoumustmakeachoice
• Besurethatyourdatarepresenta0onsupportsmethodcallsinany
order
11/4/16
108
Summary: Constructors
• Aconstructorini0alizestheobject’sinstancevariables
• Aconstructorisinvokedwhenanobjectiscreated
• Theconstructorisdefinedusingthespecialmethodname:__init_
_()
• Defaultargumentscanbeusedwithaconstructortoprovidedifferent
waysofcrea0nganobject
11/4/16
109
Summary: Method Implementation
• Theobjectonwhichamethodisappliedisautoma0callypassedtothe
selfparametervariableofthemethod
• Inamethod,youaccessinstancevariablesthroughtheself
parametervariable
11/4/16
110
Summary: Testing Classes
• Aunittestverifiesthataclassworkscorrectlyinisola0on,outsidea
completeprogram
• Totestaclass,useanenvironmentforinterac0vetes0ng,orwritea
testerclasstoexecutetestinstruc0ons
• Determiningtheexpectedresultinadvanceisanimportantpartof
tes0ng
11/4/16
111
Summary: Object Tracing
• Objecttracingisusedtovisualizeobjectbehavior
• Writethemethodsonthefrontofacard,andtheinstancevariables
ontheback
• Updatethevaluesoftheinstancevariableswhenamutatormethodis
called
11/4/16
112
Summary: Patterns for Classes
• Aninstancevariableforthetotalisupdatedinmethodsthatincrease
ordecreasethetotalamount
• Acounterthatcountseventsisincrementedinmethodsthat
correspondtotheevents
• Anobjectcancollectotherobjectsinalist
• AnobjectpropertycanbeaccessedwithageFermethodandchanged
withaseFermethod
• Ifyourobjectcanhaveoneofseveralstatesthataffectthebehavior,
supplyaninstancevariableforthecurrentstate
11/4/16
113
Summary: Patterns for Classes
• Tomodelamovingobject,youneedtostoreandupdateitsposi0on
11/4/16
114
Summary: Object References
• Anobjectreferencespecifiestheloca0onofanobject
• Mul0pleobjectvariablescancontainreferencestothesameobject
• Usetheisandisnotoperatorstotestwhethertwovariablesare
aliases
• TheNonereferencereferstonoobject
11/4/16
115
Summary: Defining Special Methods
• Touseastandardoperatorwithobjects,definethecorresponding
specialmethod
• Definethespecial__repr__()methodtocreateastring
representa0onofanobject
11/4/16
116
© Copyright 2026 Paperzz