Home > Articles > Open Source > Python

  • Print
  • + Share This
This chapter is from the book

2.18 Classes

Classes are a core part of object-oriented programming and serve as a “container” for related data and logic. They provide a “blueprint” for creating “real” objects, called instances. Because Python does not require you to program in an object-oriented way (like Java does), classes are not required learning at this time. However, we will present some examples here for those who are interested in getting a sneak peek.

How to Declare Classes

class ClassName (base_class[es]):
   "optional documentation string"
   static_member_declarations
   method_declarations

Classes are declared using the class keyword. A base or parent class is optional; if you do not have one, just use object as the base class. This header line is followed by an optional documentation string, static member declarations, and any method declarations.

class FooClass(object):
    """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__.__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 output. The __init__() method has a special name, as do all those whose names begin and end 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. __init__() can be thought of as a constructor, but unlike constructors in other languages, it does not create an instance—it is really just the first method that is called after your object has been created.

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 or member 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? It is basically an instance’s handle to itself, the instance on which a method was called. Other OO languages often use an identifier called this.

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 same syntax. They are both known as “callables.” Class instantiation uses the same functional operator as invoking a function or method.

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__.__name__ variable which, for an instance, represents the name of the class from which it has been instantiated. (self.__class__ refers to the actual class.) 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
My name is FooClass

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

  • + Share This
  • 🔖 Save To Your Account