In all of the examples so far, we have been using Python as a procedural programming language, like C or shell scripting (or most Perl scripts). You can also use Python for object-oriented programming. If you are not familiar with object-oriented programming, see Chapter 25, which explains the concepts and terminology Most of the books on Python listed at the end of this chapter also cover object-oriented programming.
To define a class, you can use the form
class MyClass (ParentClass) : def method1(self) : # insert code here, such as self.x = 1024 def method2 (self, newx) : self.x = newx def method3(self) : return self.x
This creates a class named MyClass. The (ParentClass) is optional. If it is included, MyClass inherits from ParentClass. (Python also supports multiple inheritance.)
Classes typically contain one or more methods. In the previous example, MyClass has three methods. method1 can be called without any arguments. It sets the member variable x to 1024. The second method, method2, is called with an argument, which it uses to set the value of x. The last method in this example, method3, returns the value of x.
Here’s how you might use this class in the Python interpreter:
>>> obj = MyClass() >>> obj .method1 () >>> print obj .x 1024 >>> obj .method2 ("Hello, world") >>> print obj .method3 () Hello, world
For more information about classes and objects in Python, see the Classes section of the Python Tutorial at http://docs.python.org/tut/node11.html.