Subtitle: 'We are the Knights who say..... "Ni"! '
Here we are, on the penultimate topic for this blog series post on developing in Python. As promised I am going to cover classes and importing modules today as these are closely related topics.
So firstly what is a class, A class is the core of any modern Object Oriented Programming language such as Python, most of the time, you will be writing classes. If you have a background in C or C++, C# the list goes on, many class aspects are similar, but some are different. For example, Python doesn't permit functions to exist outside the class declaration like C++;.
But the concept of data encapsulation is the same in all the modern OOP languages, so a class in Python contains data (fields for example) and operations that manipulate the data (functions). For example, a class that describes an employee would include fields like firstName, lastName, dateOfBirth, basicSalary and department, and methods that operate on the data, such as CalculateSalary() which calculates the employee's basic salary plus the overtime, for example, and another method like RaiseBasicSalary() that raises the basic salary of the employee.
The use of class allows an increased amount of code reuse for little extra effort and Python like may other languages can support inheritance and polymorphism.
Taking all the above how do we define a class in Python? Again as in the previous tutorials I am going to use a section of annotated code to try and explain the basic concepts of a class. So start a new source file in eclipse which I am sure if you are this far through you can do by now and lets get coding:
#Firstly we have to say we are defining a class, note the : at the end
class windowGlass:
#Next we have to define the initializer
def __init__(self,x,y)
self.x = x
self.y=y
tint = clear
type=standard
#Now lets define some functions against the class
def area(self):
return self.x * self.y
def tint(self, text):
self.tint = text
def type(self,text):
self.type = text
def fullDecription(self):
return "Window is ",self.x, " by ", self.y," is ",self.type," with a glass type of",self.type
What have we created here then, well basically this is a class that describes a window glass with 4 fields as properties of the window, the x and y lengths of the window glass, the tint and the glass type. The class also contains a number of functions that can be executed against the it to return things such as the area of the glass or a full description made up of all the properties.
There is one special function called __init__ which is actually called when an instance of the class is instantiated. In our case this sets a couple of defaults on the class for the type and tint and takes in the lengths of x and y.
You will also note that all the functions take in a parameter of self, this is how a class is referred to from within itself and it handled automatically by the interpreter but it has to be there for all functions to work.
So how do we use this class we have created, as stated above you need to create and instance of a class before you can use it, so lets use the class you have just entered and try a few things. Just type in this code:-
#Create an instance of the class
plainGlass = windowGlass(25,25)
Now you have your instance you can use this as a simple collection of variables and functions. Type the code below and then run the code to see what happens:-
#Print the area
print plainGlass.area()
#Print description
print plainGlass.fullDescription()
#Update the type and re-print
plainGlass.type('Frosted')
print plainGlass.fullDescription()
Thats it you now have a working class and as you can see this allows for a high level of code reuse and of course fits with the object oriented model of the world.
So if you have once class as our windowGlass you can then inherit this class and create another class which has all the functionality of the base class plus any extra that is required. Imagine we move into the stained glass business. At the end of the day a stained glass window is a glass window with a bit of color so we want all the functionality of the base class plus a bit more.
Add the following code section just below the class you have already entered:
#Inherit from the base class
class stainedWindow(windowGlass):
#Define a new initialization to override the base one
def __init___(self,x,y):
self.x= x
self.y = y
stainedPattern = "None"
#Add a new method to set the stained pattern
def stainedPattern(self,text):
self.stainedPattern = text
#Override the description method so it includes the new text
def fullDecription(self):
return "Window is ",self.x, " by ", self.y," is ",self.type," with a glass type of",self.type, " with a pattern of ", self.stainedPattern
OK, now we have our class if you add the code below you will see all the methods from the base class are available plus new overridden methods
#Create an instance of the class
glass = stainedGlass(25,25)
#Print the area
print glass .area()
#Print description
print glass.fullDescription()
#Update the type and re-print
glass.type('Frosted')
glass.stainedPattern('Sunrise')
print glass.fullDescription()
As you can see classes have a wide array of uses and now we can define them lets look at the best way to maximize re-use. That is to say creating a module with the class in it and then importing it where it is needed.
So how do you create a module, well it couldn't be easier so lets create one. To you current solution file in Eclipse add a new source file called moduleTest.py and cut and paste both the class definitions you have just created into that file and then save it. Thats it, you have created a module.
Now to use it in your main source file, it is simply a case of adding an import statement to the top of the source file, in fact it can be anywhere in the source file but lets keep with standards and put our at the top. You may already see a couple of import lines at the top,if so add this line afterwards, if not just add it to the top:-
import moduleTest
and to get all our code working again it is a simple case of locating the two class instantiation lines and adding the module name to them as shown in the example below:-
glass = moduleTest.stainedGlass(25,25)
Once you have changed both lines you should be able to re-run your program with no issues.
There are a couple of small other points worth noting, you can for example just import certain items from a module if you so wish using the following code as an example, this has the advantage that you can then from the moduleTest. from all your following code:-
from moduleTest import stainedGlass
Thats it for today we are almost there, you will hopefully by now be well on your way to developing in Python and for my last post in this series I will cover error handling and file access. I know we never read from text files or ever have code that generates errors but just in case I think I should cover it.......