2.17. Classes

A class is merely a container for static data members or function declarations, called a class's attributes. Classes provide something which can be considered a blueprint for creating “real” objects, called class instances. Functions which are part of classes are called methods. Classes are an object-oriented construct that are not required at this stage in learning Python. However, we will present it here for those who have some background in object-oriented methodology and would like to see how classes are implemented in Python.

How to Declare a Class

							class class_name[( base_classes_if_any)]:
    "optional documentation string"
    static_member_declarations
							method_declarations
						

Classes are declared using the class keyword. If a subclass is being declared, then the super or base classes from which it is derived is given in parentheses. This header line is then terminated and followed by an optional class documentation string, static member declarations, and any method declarations.

							class FooClass:
     'my very first class: FooClass'
     version = 0.1            # class (data) attribute

     def __init__(self, nm='John Doe'):
         'constructor'
         self.name = nm       # class instance (data) attribute
         print 'Created a class instance for', nm

     def showname(self):
         'display instance attribute and class name'
         print 'Your name is', self.name
         print 'My name is', self.__class__   # full class name

     def showver(self):
         'display class(static) attribute'
         print self.version  # references FooClass.version

     def addMe2Me(self, x):  # does not use 'self'
         'apply + operation to argument'
         return (x + x)

In the above class, we declared one static data type variable version shared among all instances and four methods, __init__(), showname(), showver(), and the familiar addMe2Me(). The show*() methods do not really do much but output the data they were created to. The __init__() method has a special name, as do all those whose name begins and ends with a double underscore ( __ ).

The __init__() method is a function provided by default that is called when a class instance is created, similar to a constructor and called after the object has been instantiated. Its purpose is to perform any other type of “start up” necessary for the instance to take on a life of its own. By creating our own __init__() method, we override the default method (which does not do anything) so that we can do customization and other “extra things” when our instance is created. In our case, we initialize a class instance attribute called name. This variable is associated only with class instances and is not part of the actual class itself. __init__() also features a default argument, introduced in the previous section. You will no doubt also notice the one argument which is part of every method, self.

What is self? Self is basically an instance's handle to itself. (In other object-oriented languages such as C++ or Java, self is called this.) When a method is called, self refers to the instance which made the call. No class methods may be called without an instance, and is one reason why self is required. Class methods which belong to an instance are called bound methods. (Those not belonging to a class instance are called unbound methods and cannot be invoked [unless an instance is explicitly passed in as the first argument].)

How to Create Class Instances

>>> foo1 = FooClass()
Created a class instance for John Doe

The string that is displayed is a result of a call to the __init__() method which we did not explicitly have to make. When an instance is created, __init__() is automatically called, whether we provided our own or the interpreter used the default one.

Creating instances looks just like calling a function and has the exact syntax. Class instantiation apparently uses the same functional operator as invoking a function or method. Do not get confused between the two, however. Just because the same symbols are used does not necessarily mean equivalent operations. Function calls and creating class instances are very different animals. The same applies for the + operator. Given a pair of integers, it performs integer addition; given a pair of floating point numbers, it performs real number addition; and giving it two strings results in string concatenation. All three of these operations are distinct.

Now that we have successfully created our first class instance, we can make some method calls, too:

>>> foo1.showname()
Your name is John Doe
My name is __main__.FooClass
>>>
>>> foo1.showver()
0.1
>>> print foo1.addMe2Me(5)
10
>>> print foo1.addMe2Me('xyz')
xyzxyz

The result of each function call is as we expected. One interesting piece of data is the class name. In the showname() method, we displayed the self.__class__ variable which, for an instance, represents the name of the class from which it has been instantiated. In our example, we did not pass in a name to create our instance, so the 'John Doe' default argument was used. In our next example, we do not use it.

>>> foo2 = FooClass('Jane Smith')
Created a class instance for Jane Smith
>>> foo2.showname()
Your name is Jane Smith
__main__.FooClass

There is plenty more on Python classes and instances in Chapter 13.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset