Python Workshop: Part 2

Slashdot it! Delicious Share on Facebook Tweet! Digg!
©Kirsty Pargeter, Fotolia.com

©Kirsty Pargeter, Fotolia.com

EverythingIs An Object

After the introduction to Python in the previous issue, this article deals with object orientation. As a practical exercise, you'll be programming a simple graphical user interface.

Before you design a GUI with Python, you need to understand a few basics about object-oriented programming. That's because object-oriented programming is what you'll need to create a graphical user.

Shirts Are Simply Objects

Because everything is an object in Python, you often need to design your own objects before you can use them in your program. Admittedly, this is a somewhat abstract concept. I'll use an example from daily life to make it easier to understand. A shirt is an object. Object-oriented code can represent this shirt as an abstract concept as shown in Listing 1. As always, you can find the source code for the examples on the Ubuntu User website [1].

Listing 1

shirt.py

01 # -*- coding: utf-8 -*-
02
03 class shirt(object):
04     """A shirt that will be washed repeatedly.
05     """
06     def __init__(self, size, color):
07         self.size = size
08         self.color = color
09         self.washes = 0
10     def wash(self):
11        """Count how often I was washed.
12        """
13        self.washes += 1

Right on the first line, you specify the file encoding with # - * - coding: utf-8 - * - , which allows you to use characters from all languages in your (unicode) strings and comments. Of course, you need to save this file in the indicated encoding or the program will fail to start. How you go about this depends on the editor you use. With Gedit, you can use the menu item File | Save as and choose the encoding.

The line class Shirt(object) defines the new class, Shirt , which inherits from the base class object . Although there are good reasons why you need to put object there, you can take it as a convention without my going into the details. The keyword class defines new types of objects. Classes are at the core of object-oriented programming. The box "Class, Instance, Attribute, Method" provides some definitions of the different objects that are important when working with classes.

Class, Instance, Attribute, Method

Class: Classes define new datatypes and help represent things in real life in programs. The Shirt class has a size , a color , and a number of washes .

Instance: A white shirt in size 16 would be an instance of the Shirt class. There can be any number of instances in a program. The class thus defines general criteria for shirts and instances are the concrete manifestation of these criteria.

Attribute: Classes and instances have attributes. The shirt_1 instance has the attributes size , color , and number of washes , which have specific values. Every instance, that is, every shirt, has individual attributes and can have a different color and size.

Method: Technically speaking, methods are functions that you define inside a class. A method usually does something. The wash() method "washes" your shirts and increments the wash counter.

Next comes the method __init__ that contains the attributes size , color , and washes . Python automatically calls __init__ and initializes the attributes with values when you create a new instance of the class.

You're already familiar with methods like __init__ because methods are functions that you define inside a class. Remember, for example, the function get_total_size() from the previous workshop [2]. The first argument to a method is always self. , which is a placeholder for the instance you create later. You need a placeholder here, because when you define a class and its methods, you don't know the instance yet. The wash() method defined on line 10 increments the counter for the washes attribute.

The next step is to go to the interactive prompt and wash a digital shirt. Import the module shirt (the file shirt.py ) and create a new instance in the Shirt() class defined in it:

>>> import shirt
>>> shirt_1 = shirt.Shirt(16, 'white')

You then access the attributes color and size of the instance shirt_1 :

>>> shirt_1.color
'white'
>>> shirt_1.size
42

You can wash the digital shirt and see the results as the wash counter increments:

>>> shirt_1.washes
0
>>> shirt_1.wash()
>>> shirt_1.washes
1
>>> shirt_1.wash()
>>> shirt_1.washes
2

You then create a second instance:

>>> shirt_2 = shirt.Shirt('L', 'green')
>>> shirt_2.size
'L'
>>> shirt_2.color
'green'

And, the wash results

>>> shirt_2.washes
0
>>> shirt_2.wash()
>>> shirt_2.washes
1

will be shown as before.

A Graphical User Interface

With Python, you can use many different GUI libraries, among them GTK, WxWidgets, and Qt. Basically, you use all these libraries in a similar way using the same programming style (see the "Programming Paradigms" box).

Programming Paradigms

You can use various programming styles and paradigms to solve problems in programs. In the previous article, you used the procedural paradigm (perhaps without knowing it). Such a program consists of instructions that the computer executes one at a time in a sequence of steps. A procedure is a self-contained unit or, in this case, a function beginning with def . These procedures structure a program, which executes them in sequence.

Objects, such as instances, are of great importance in object-oriented programming. Instances contain data in the form of attributes (the size and color of shirts) and behave in a certain way (wash shirts). These objects interact with each other and often can represent real-world objects better than in other programming styles.

For your graphical interface, you'll use event-driven programming. Your program won't run sequentially but will pause and respond to triggering events. For example, you can call the method calculate() by clicking the Calculate Size button. This triggers an event. During programming, it isn't clear yet if and when you will access a particular method when you use the program. For example, if you close the program right after opening it, there may not be an event to execute the method.

This example uses PySide [3], which makes the powerful Qt library accessible for Python programmers. PySide is open source (LGPL) and works on Mac OS X as well as on Windows.

To install PySide, enter the command:

sudo apt-get install python-pyside

Installation requires the administrator password and takes some time. Once you've installed it, type >>> import PySide at the interactive prompt. If you don't get an import error, you have successfully installed this library.

Buy this article as PDF

Express-Checkout as PDF

Pages: 4

Price $0.99
(incl. VAT)

Buy Ubuntu User

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content