Press enter to skip the top menu

Python Programming

Classes and Objects

NCEA Compatibility

Module: as91906 Use complex programming techniques to develop a computer program

Requirements: object-oriented programming using class(es) and objects defined by the student

Relevant Implications:

Go to top

Learning Outcomes

On completion of this section you will know:

Go to top

Introduction

Python is an object oriented language, yet we have progressed this far without ever mentioning the word object. We have managed to do this by exploiting the fact that it also is capable of procedural programming, which is what we have been doing up until now. Thus we were able to do very limited programming that still enabled us to become familiar with the essential ideas and structures that underlie all programming such as: Variables, Operators and operands, Decision constructs, Loop constructs, Functions, Modules and File and database processing

Now that we have got those under our belt we shall move on to examine the first OO topic which is objects themselves and their underlying classes. In order to do so we shall revert to the payroll application we been working with up to now, but this time we shall put all of the processing into a classes

Go to top

Classes

What is a class?

In object-Oriented programming a class is a program code template for creating objects. A class contains many of the concepts that you are already familiar with in procedural programming such as variables and functions.

Within a class variables are referred to as properties, fields, data members or attributes. Functions are generally referred to as methods. Here we shall adopt data members for variables and methods for functions.

How does a class differ from the procedural code we have been using up to now?

Generally the data members of a class are declared as being private to that class. This means that no code that is external to the class can see them. They are, however visible to the methods of the class.

The class methods are generally similar to the methods you have met up until now, except that like the data members, they can be private to the class or public – in which case they can be seen by code outside of the class.

Most classes have a special method commonly known as the constructor. What is special about this method is that it is run automatically once an object of the class is created and once it has finished it cannot be called again for that object. (Of course it can run for other objects of the same class, but again it runs only once for each of those objects.) In our examples we shall use the constructor to populate the class’ data members and call the methods for processing the same members.

Go to top

A Class Layout

Our class example will be based on the programming examples that we have been using up until now.

We shall start our class by defining its data members. As it will be based on previous examples the data members will consist of IRD number, name, hours, rate, gross, tax and net. All of those variables will be declared as private to the class, so that no extremal code may be able to corrupt them.

After the data members we define the constructor. This constructor will have arguments for populating the data members for ird number, name, hours and rate. It will not accept values for the gross, tax or net as it will the business of the class itself to calculate those values.

Once the constructor has populated the appropriate data members it will call an internal private function that will calculate the gross tax and net and store the results – i.e. the gross, tax and net - in the remaining data members.

Although we do not want any external code to have direct access to the class’ data members so that they cannot be corrupted, we still want the external code to be able to read their values. For that purpose we shall have a series of methods that will return the values of the private data members to external code.

Most of Java’s classes have a toString() method that returns all of the internal data members of that class to us without revealing any of the class’ internal structure. We shall implement a similar functionality here with our own stString() function.

Go to top

Employee Class

Below is the code for our class, based on the specifications above.

Listing 1
                    
                        class Employee:
                            __strIRD=""
                            __strName=""
                            __floatHours=0.0
                            __floatRate=0.0
                            __floatGross=0.0
                            __floatTax=0.0
                            __floatNet=0.0
                        
                            def __init__(self, ird, nme, hrs, rt):
                                self.__strIRD = ird
                                self.__strName = nme
                                self.__floatHours = hrs
                                self.__floatRate = rt
                                self.__calculate()
                        
                            def irdValue(self):
                                return self.__strIRD
                        
                            def nameValue(self):
                                return(self.__strName)
                        
                            def hoursValue(self):
                                return self.__floatHours
                        
                            def rateValue(self):
                                return self.__floatRate
                        
                            def grossValue(self):
                                return self.__floatGross
                        
                            def taxValue(self):
                                return self.__floatTax
                        
                            def netValue(self):
                                return self.__floatNet
                        
                            def __calculate(self):
                                self.__floatGross = self.__floatHours * self.__floatRate
                                self.__floatTax = self.__floatGross * 0.25
                                self.__floatNet = self.__floatGross - self.__floatTax
                        
                            def toString(self):
                                strOutput = "IRD is "+self.__strIRD+"\n"
                                strOutput += "Name is " + self.__strName+"\n"
                                strOutput += "Hours worked is "+str(self.__floatHours) + "\n"
                                strOutput += "Hourly rate is " + str(self.__floatRate) + "\n"
                                strOutput += "Gross is " + str(self.__floatGross) + "\n"
                                strOutput += "Tax is " + str(self.__floatTax) + "\n"
                                strOutput += "Net is " + str(self.__floatNet) + "\n"
                                return strOutput
                        	
                        payroll= Employee("123123","Tom Thumb", 20, 40)
                        print(payroll.toString())
                    
                    

In lins 2 to 8 above the data members for the class are defined. Notice that their names are similar to those we have used in previous examples, apart from the fact that all of the data member names are preceded by double underscores. These underscores indicate that all of those data members are private to the class Employee, i.e. they cannot be seen by any code outside of the class itself.

Lines 10 to 15 contain the class' constructor, i.e. the method that runs automatically when an object of the class is created. The class has five arguments. The first argument, self is mandatory. It must be the first argument of any method that is defined inside the class. The other four, ird, nme, hrs and rt, as their names imply, will hold the values for the ird number, employee's name, hours and rate. Lines 11 to 14 assigns the values of each of those four arguments to the data members defined in lines 2 to 5. Finally line 15 call the private method __calculate() to calculate the values of the gross, tax and net.

Between lines 17 and 36 we have a series of methods that return the values of the different private data members of the class. The first one, irdValue() which spans lines 17 and 18 has no double underscores in front of its name. This means that it is public, i.e. it can be seen by code that is external to the class. Like the constructor, this method also has self as its first argument. Its only command at line 18 returns the value of the data member strIRD. Again notice that strIRD. is preceded by self, indicating that we are referring to the data member strIRD., which has been declared inside the the class Employee.

Our description of the method irdValue() also applies to the other seven methods that follow it.

Next we examine the method __calculate() that spans lines 38 to 41. The double underscore preceding its name indicates that it is private to the class Employee. It also has the obligatory self as an argument, indicating it is part of the class Employee. All of the data members in its body are also preceded by self.

Finally we examine the method toString(). At lines 44 to 50 it builds up the string variable strOutput using label, the value of the class members and the newline character to build up a string containing the values of all of the class' data members preceded by a descriptive label, with each data member and its own label on a single line. Line 51 returns the value of the completed string to whichever external command which called it.

The class Employee ends at line 51.

Lines 53 and 54 comprise the external code of our application. It is fairly small, in comparison to the size of the class Employee. This is the case in most object oriented applications since most of the code is in the classes' methods and the procedural code is generally confined to calling those methods.

At line 53 an object of the class Employee is created. This class is named payroll. When the object is created the values "123123","Tom Thumb", 20 and 40 are passed to the object. Recall we stated earlier that when an object is created, its constructor runs automatically. This constructor starts at line 10. Prior to its running the values passed to the object are copied into the arguments ird, nme, hrs and rt. Once the constructor runs the same values are stored in the class' data members and then the __calculate() method is called to calculate the values for the gross, tax and net, which it stores in the last three data members.

Back to line 54. Here the toString() method of payroll is called, which returns the labelled values from the object's data members and then passes them to the console for human viewing.

A sample output is shown below.

Fig 1
Go to top

Retrieving individual values

In listing 1 above we extracted data from the object using the toString() method. This was fine for getting all of the data from the object quickly. On the other hand if we wanted individual items such as the ird number or the gross pay, it would be difficult to extract them from the toString() method.

In order to retrieve individual items we use the methods from lines 17 to 36.

Listing 2
                    
                        print("IRD Number ",payroll.irdValue())
                        print("Name ",payroll.nameValue())
                        print("Hours ",payroll.hoursValue())
                        print("Rate ",payroll.rateValue())
                    
                    

If we were to add the extra set of lines above to Listing 1 we could extract the values for the individual items.

>
Go to top

Summary

In this introduction to Object Oriented programming we have introduced the fact that there are two aspects to the discipline: classes and objects. Earlier we stated that classes are templates from which objects are constructed. Thus they can be compared to blueprints from which buildings or items of furniture can be constructed, or a recipe from which a meal can be prepared. In those analogies the blueprints and recipes would correspond to he classes while the buildings, furniture items or the prepared dishes would be the physical objects.

Getting back to classes and objects, the classes would exist as text files stored in a computer's external storage whereas the objects would only exist as blocks in the computer's RAM during run time.

Go to top

Exercises

Exercise 1

Copy the code from listing 1 into a document and save it as a Python file. Run it a number of times, changing the values at line 53 each time. Double check that the output is correct.

Exercise 2

Extend the application by creating more objects after line 54. Pass data to the constructors as shown in line 53 but ensure that the data values are different each time. Use the toString() method to extract all of the data from each one.

Exercise 3

Using Listing 2 as an example extract the values of the gross, tax and net from all of the objects you created in Exercise 2 and print them with appropriate labels.

Go to top

Revision

Fill the blanks

Go to top