ObjectOriented, Programming,in,Python,

Transcription

Object- nceandInformaDcs,Dublin)

ClassesandObjectsObject- edas"objects" PythonsupportsOOPthroughtheprovisionofclasses. Terminology pecificname,whichrepresentsanabstractconcept. ithaclass. Object:Asingleconcreteinstancegeneratedfromaclass

created.

InstancesofClasses

CreaDngClasses Defining a class in Python is done using the ents.General FormatClass dataattributesclass Classname :data1 value1.dataM valueMdef function1 (self,arg1,.,argK): block .def functionN (self,arg1,.,argK): block Classmemberfunctions

DefiningFuncDonsinClasseslass definitionblockblockcan nctifuncDons.ese represent the functionality or behaviors tha ththe class.thatareassociatedwiththeclass. class Maths:.def subtract(self,i,j):.return i-j.def add(self,x,y):.return x yArgument(self)referstotheobjectitselfss functions differ from standard Python functions

CallingFuncDonsinClasses UsingClassFuncDonsfromOutsideaClassss FunctionsfromOutsidea x:are referencedthe bdotsyntax: objectName . methodName ()me . funcName () m Maths() m.subtract(10,5)5 m.add(6,7)13No need tospecify value forself, Python doesthis automaticallyass Functions from Inside a Classerring to functions

. funcName ()No needto to m mMaths()No need Maths()specifyvaluefor forspecifyvalue esdoesPython5 5this thisautomaticallyautomatically lass13 ithselfunctionsfromInsidea Classs FunctionsfromInsidea Class(e.g.self.subtract())to functionsringto functionsclass,a class,s prefixthethewaysprefixwithwithselfmeselfract()) )subtract() classMaths:classMaths:. . def defsubtract(self,i,j):subtract(self,i,j):. .returni-j i-jreturn. . . def deftestsub(self):testsub(self):. l TellPythonto usefunctionPythonto usefunctionassociatedwithwiththis thisobjectassociatedobject8

AKributesClass attributeClass attributedefinedat top ofclass Person:defined at top of class Person:class.company "ucd".company "ucd"class. Person() p1 p1 Person() p2 Person() p2 Person() p1.age 35 p1.age 35 print p2.age 23print p2.age23 p1 Person() Person() p1 p2 Person() p2 p1.company Person() "ibm"print p2.company p1.company "ibm"'ibm' print p2.company'ibm'defdef init (self):init (self):self.age23self.age 23Instance attributeInstance attributedefinedinsidea classdefinedinsidea s ageChangetotoinstanceinstanceattributeaffects only the associatedaffects only the associatedinstance (p2)instance (p2)Change to class attribute companyaffects(p1 and companyp2)Changealltoinstancesclass attributeaffects all instances (p1 and p2)

ConstructorWhen an instance of a class is created, the class constructorfunction is automatically called. rTheconstructoris alwaysnamedinit ()funcDonisautomaDcallycalled.It contains code for initializing a new instance of the class to a t ()attribute lizingnewinstanceofistheclasstoaIf ficiniDalstate(e.g.seTnginstanceaKributevalues). class Person:.def init ( self, s ):.self.name s.def hello( self ):.print "Hello", self.name t Person("John") t.hello()Hello JohnConstructor function takinginitial value for instanceattribute nameCalls init ()on Person

nshipsofthetype"xisay"(e.g."atriangleisashape")

ass.

CreaDngSubclasses

Simple superclass class Shape:.def init ( self ):.self.color (0,0,0)Simple subclassinheriting fromShape class Rectangle(Shape):.def init ( self, w, h ):.Shape. init ( self ).self.width w.self.height h.def area( self ):.return self.width*self.height 10 5 50 (0,r1 Rectangle( 10, 5 )print r1.widthNeed to callconstructorfunction insuperclassConstructobject instanceprint r1.heightprint r1.area()print r1.color0, 0)Inheritedattribute

superclass.

original superclass by "overriding" functions(i.e. declaring functions in the subclass with the same name).OverridingNote: Functions in a subclass take precedence over functionsin a superclass.class Counter:def init (self):self.value 0def increment(self):self.value 1 cc CustomCounter(4) cc.increment() cc.print current()Current value is 4class CustomCounter(Counter):def init (self,size):Counter. init (self)self.stepsize sizeOverridingdef increment(self):self.value self.stepsizeCalls increment()on CustomCounternot Counter

allowing us tomodelof the hipsoft"xhehastypea"x(e.g.a s Department:def init ( self ):self.students []class Student:def init ( self,last,first ):self.lastname lastself.firstname firstdef enroll( self, student ):self.students.append(student) compsci Department() compsci.enroll( Student( "Smith", "John" ) ) compsci.enroll( Student( "Murphy", "Alice" ) ) for s in compsci.students:.print "%s %s" % (s.firstname,s.lastname).John SmithCreate Studentinstances and addto Departmentinstance

eoutward"appearance"isthesame.

Two objects of different classes but supporting the same set of Polymorphismfunctions or attributes can be treated identically.The implementations may differ internally, but the outward"appearance" is the same.Two different classes that contain the function area()class Rectangle(Shape):def init (self, w, h):Shape. init (self)self.width wself.height hdef area(self):return self.width*self.heightInstances of the two classes can betreated identically.Result of area() in RectangleResult of area() in Circleclass Circle(Shape):def init (self, rad):Shape. init (self)self.radius raddef area(self):return math.pi*(self.radius**2) l [] l.append( Rectangle(4,5) ) l.append( Circle(3) ) for someshape in l:.print someshape.area().2028.2743338823

ObjectOriented, Programming,in,Python, (Taken,and,Adapted,from,the,course, notes,of,Dr.,Greene,o