dreamsys software

Python Scripting Tutorial

Classes


When your scripts start to grow and your set of functions grow, you will start to notice that many of your functions are related, they work on data that is common between them and they really represent an entity collectively. This is where it is usually a good idea to create a class. Let's say that our program, deals with a user name, age, birth date, height, weight and variables like that and there are methods in our program such as readUserAge, readUserName, updateUserAge, etc. A good place to start would be to add a class "User" which is done by using the class keyword.

Now let's create a simple script which will ask the user for information on a user, store it to a file and load the user info from the file. We will have it run with two options, one is that the user enters the info, and another is that it just loads the user from the file and displays it.

#!/usr/bin/env python
import sys

class User:
    name = ""
    age = 0
    height = 0
    weight = 0
    
    def display(self):
        print ''
        print 'User Information:'
        print 'User Name  :', self.name
        print 'User Age   :', self.age
        print 'User Height:', self.height
        print 'User Weight:', self.weight
    
    def loadFromInput(self):
        self.name = raw_input('Enter User Name: ')
        self.age = int(raw_input('Enter Age: '))
        self.height = float(raw_input('Enter Height (in feet): '))
        self.weight = int(raw_input('Enter Weight: '))
    
    def save(self):
        f = open('user.info','w')
        f.write(self.name + '\n')
        f.write(str(self.age) + '\n')
        f.write(str(self.height) + '\n')
        f.write(str(self.weight) + '\n')
        f.close()
        
    def loadFromFile(self):
    	f = open('user.info', 'r')
    	self.name = f.readline().rstrip()
    	self.age = int(f.readline())
    	self.height = float(f.readline())
    	self.weight = int(f.readline())

        
theUser = None

if len(sys.argv) > 1 and sys.argv[1] == 'READ':
    theUser = User()
    theUser.loadFromFile()
else:
    theUser = User()
    theUser.loadFromInput()
    theUser.save()
    
theUser.display()

the first new thing you will run into here is the keyword class, which is used to define a new class called "User". Under this we first create the variables which belong to the class. What does the user have? It has a name, age, height and weight. Next we define the methods which will work on the user. What do we want to do with a user? We want to load it from a file, load it from user input, save it and display it. So there are methods for each of these operations.

We declare class methods the same as we do regular methods except that they are indented under the class level and they take at least one parameter (self), which is the instance of the class that they will be working on. The methods can be declared in any order but here we have ordered them in the order that they will typically be called.

In the display() function, we are simply printing the data of the class, notice that we use the self variable before the variable name. The loadFromInput() function uses the raw_input function that we are already familiar with to load the user info from the console input.

The save() method uses a new function, open, which can be used to open a file for reading or writing. In the save method, we use 'w' as the 2nd parameter, which indicates opening the file as the first parameter in "write" mode. Then we continue to call the method write on the file object returned to write each of the variables followed by a return.

Finally, the loadFromFile() method will open the file in read mode by using the parameter 'r'. It will then use the function readline to read each of the variables from the file.

Below the class we show how the class is actually used. First we initialize the "theUser" variable with the None keyword meaning that it is not yet created. Now we check if there is a parameter sent to the script with the text "READ", if so we will read from the file that was created when the user was saved, if not then we will ask the console for input and create and save the user.

So now, let's run the script once to create the user and then again to read the user from the file:

$ ./userTest.py
Enter User Name: Joe
Enter Age: 25
Enter Height (in feet): 5.9
Enter Weight: 170

User Information:
User Name  : Joe
User Age   : 25
User Height: 5.9
User Weight: 170
$ ./userTest.py READ

User Information:
User Name  : Joe
User Age   : 25
User Height: 5.9
User Weight: 170

Next you will learn how to manipulate strings.

Prev (Functions) | Next (Strings)


Blog Entries
Blob Entry 1
Blob Entry 2
Blob Entry 3
Blob Entry 4
Blob Entry 5
Blob Entry 6