Web Developer's Virtual Library: Encyclopedia of Web Design Tutorials, Articles and Discussions


WDVL Newsletter

jobs.webdeveloper.com

e-commerce
Partner With Us















Developer Channel
FlashKit.com
JavaScript.com
JavaScriptSource
Developer Jobs
ScriptSearch
StreamingMediaWorld
Web Developer's Journal
Web Developer's Virtual Library
WebDeveloper.com
Webreference
Web Hosts
XMLfiles.com

internet.com
IT
Developer
Internet News
Small Business
Personal Technology

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers


A First Look at Python Classes

Bookmark and Share

July 28, 2009

This article will explore the mechanics of classes in Python.

Introduction

To begin a discussion of classes, I think we should look back to the 'C' language. In many ways, C is the parent of most modern computer languages. Most interpreters and compilers are written in C. Most of the libraries of the scripting languages are written in C. Therefore, I could argue that modern languages are an abstraction of C in the same way that C is an abstraction of assembler.

C has a feature called a 'struct'. Struct allows a group of variable assignments, of different data types, to be collected under a single name. The variables can be pointers to functions. Many 'instances' can be declared of a struct. The instance can be referred to by a pointer. The pointers can be stored in arrays. The structs can contain other structs.

C++, and later Java, expanded the functionality of a struct in something called a class. Among other things, functions (methods), could now be part of a class. And the concept of 'private' data was created. Then languages like Python, Ruby and PHP relaxed the strict definitions of what a class should or has to be. The result is that today, we have a very useful mechanism or structure called a class, with commonality between languages.

This article will explore the mechanics of classes in Python. It will not discuss the whole theory of object oriented programming. This article may serve, if you come from a C backround, to show that a class is just an enhanced struct.

In a sense, when you run a Python program, you are creating an instance of a class. Everything in Python is represented by a class. For simplicity, we will ignore operators like '+', and keywords like 'and'.

When you create a variable, you create an instance of a class.

$ python
Python 2.5.1 (r251:54863, May  2 2007, 16:56:35)
>>> a = 'abc'
>>> a.__class__
<type 'str'>
>>> a.__contains__
<method-wrapper '__contains__' of str object at 0x82968a0>
>>> dir(a)
['__add__', '__class__', '__contains__', '__delattr__', 
'__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', 
.........
'__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 
'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 
'index', 'isalnum', 'isalpha', 'isdigit'........]

The variable a is the name in the namespace for an instance of the class 'str', and it has properties(data) and methods(functions).

Let us look at the simplest use of a class, an empty class for the storing of things.

#!/usr/bin/env python
# sample.py

class my_dummy:
   pass
store = my_dummy()
print 'line 1 ',dir(store)
store.myname = 'phillip'
print 'line 2 ',dir(store)
print 'line 3 ',store.myname

$ ./sample.py
line 1  ['__doc__', '__module__']
line 2  ['__doc__', '__module__', 'myname']
line 3  phillip

I have declared a class and named it my_dummy. The keyword 'pass' gets me out, leaving an 'empty' class. Then I declare an instance of the class and name it 'store'. A dir() of the instance shows it to have two, properties. These are empty. Then I give the instance a property which I name 'myname'. Another dir() shows that the property has been added. The last line shows that I can access the property via the class instance.

There are times in Python when you may need to resort to the very irritating 'global'. A 'dummy' class is a nice way to have one global make your variables accessible from anywhere.

Now let us look at classes in depth. The following sample code is not intended to represent a simplified design of anything real. It is merely for the purpose of illustrating the mechanics of classes.

 1 #!/usr/bin/env python
 2 
 3 class AEmployee:
 4     def __init__(self,name):
 5         self.__name = name
 6     def getName(self):
 7         return self.__name
 8 # etc
 9 
10 class HourlyEmployee(AEmployee):
11     def __init__(self,name='',permTemp='P',fullPart='F',rate=10.00,curHours=0):
12         self.__name     = name
13         AEmployee.__init__(self, self.__name)
14         self.__permTemp = permTemp
15         self.__fullPart = fullPart
16         self.__rate     = rate
17         self.__curHours = curHours
18         self.__wage = 0
19         self.dirty    = True
20     def getWage(self):
21         if self.dirty:
22             self.__setWage()
23             self.dirty = False
24         return self.__wage
25     def __setWage(self):
26         self.__wage = self.__rate * self.__curHours
27
28 class myMain:
29     def __init__(self,emplist):
30         self.__emp = []
31         for emp in emplist:
32             self.__emp.append( HourlyEmployee(
33                  emp[0], emp[1], emp[2], emp[3], emp[4] ))
34         self.doStuff()
35     def doStuff(self):
36         for emp in self.__emp:
37             print emp.getName(), emp.getWage()
38
39 if __name__ == '__main__':
40     emplist = [
41                ['bob','P','F',15.00,40],
42                ['carol','P','F',20.00,40],
43                ['ted','T','P',15.00,40],
44                ['alice','T','P',20.00,30]
45           # obviously, women make more than men
46                ]
47     runMain = myMain(emplist)

Line 3 is a class definition. Purely as convention, I have begun the name with 'A'. This signifies that it is an abstract class. That is a class which is intended to be a 'parent' class and is not useful by itself.

Line 4 is the method __init__, which is Python's reseverved name for a constructor. This means that this method will be automatically executed when the class is 'instantiated'.

A First Look at Python Classes
A First Look at Python Classes - Cont.



Up to => Home / Authoring / Tutorials / Python




Jupiter Online Media: internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and Jupiter Online Media

Jupitermedia Corporate Info


Legal Notices, Licensing, & Permissions, Privacy Policy.

Web Hosting | Newsletters | Tech Jobs | Shopping | E-mail Offers