Python Class & Objects
Python Class & Objects
c G A Vignaux 2007-8 Revision : 1.23
I “A class is a user-defined type which you can instantiate I a blueprint or plan that
to obtain instances, meaning objects of that type.” I describes objects of the class.
I For example you could have a class of StudentRecords in a I Each object can have its own data.
program. You can instantiate many instances of student I Each object can have its own methods.
records to keep data on the students in the University. I But, defining a Class does not itself define any objects
Defining a Class A Class definition
class Ship:
"""A class of ships"""
Use the Class statement: def __init__(self,nm=’’):
self.name = nm
class ClassName: self.load = 0
<statement-1> self.location = (0.0,0.0)
.
<statement-N> def setload(self,ld):
self.load = ld
box = [thing1,thing2]
thing1=Thing(’Thing1’,’Red’)
thing2=Thing(’Thing2’,’Blue’)
Add a str () A docstring
Add a str method to the definition. I It is good practice to give every class a documentation string.
class Thing: I Called a docstring
def __init__(self,nm,col): I This is placed first in the class definition.
self.name = nm I There really should be a docstring for every method as well
self.colour = col (left out here for space reasons)
def __str__(self): class Thing:
return self.name+’ is ’+self.colour ’’’ Objects of this class do not do much
’’’
thing1=Thing(’Thing1’,’Red’) def __init__(self,nm,col):
print thing1 self.name = nm
self.colour = col
This gives
def __str__(self):
Thing1 is Red return self.name+’ is ’+self.colour
class Ship:
"""A class of ships"""
def __init__(self,nm=’’):
self.name = nm arahura = Ship(’Arahura’)
self.load = 0 arahura.setload(1000)
self.location = (0.0,0.0)
arahura.setlocation((120.0, 99.0))
def setload(self,ld): print arahura
self.load = ld
This gives
def setlocation(self,loc=(0.0, 0.0)):
self.location = loc Arahura is at (120.0, 99.0) with 1000 tonnes
def __str__(self):
return self.name+’ is at ’+str(self.location)+
’ with ’+str(self.load)+ ’ tonnes’
Summary of Methods and Fields Importing a Class from a module