< BACKMake Note | BookmarkCONTINUE >
152015024128143245168232148039199167010047123209178152124239215162147039203229248005010102

Python Classes and Instances

In Python, a class is a user-defined data type, and as in most other languages, you define Python classes using the keyword class.

					
class <class name>:
    <class statements>

				

The class statements section contains any valid Python statement that defines class constants or class methods. Note that the contents of the variable namespace formed by executing the commands in the class statement make up the class dictionary.

Two ways to create classes are

  • You can define it from scratch.

    							
    class <class name>:
        ["documentation text"]
        <class statements>
    
    						
  • You can create a new class that inherits properties of other classes. This is called subclassing, and you will learn more about it later in this chapter.

    							
    class <class name> [(baseclass1, baseclass2, …)]:
        ["documentation text"]
        <statements>
    
    						

A class definition starts at the keyword class and ends at the last line of the indented block of code that goes underneath.

Methods and class constants define a class namespace. Usually, a class has several methods, and they must all start with the keyword def.

Tip

Methods are how to call functions in a class.



All methods have the additional argument self as the first argument in the method header—The convention is to call it self because it could be any other name. Python's self argument is similar to the this keyword in C++. Its function is to transport a reference of the object in a way that when a method is called, it knows which object should be used.

					
>>> class a:
…     def __init__(self):
…         print self
…
>>> b = a()
>>> b
<__main__.a instance at 795420>

				

In order to reference an attribute within a class, you need to use either self.attribute or classname.attribute. Note that the self.attribute syntax is to remove ambiguities between instance variables and function local variables. Also, self.attribute and classname.attribute are different. The second sets class attributes, which will affect all instances of the class.

					
>>> class c:
…     def __init__(self, value=None):
…         self.name = value
…

				

To reference an attribute while using a class instance, you have to use instancename.attribute.

					
>>> obj.name

				

A class can also contain class variable assignments. These variables are shared by all the class instances. Class variables are useful when the assignment of default values to instances is required. Class variables do not have the self. prefix.

For example

					
>>> class Student:
…    default_age = 20                      # class variable
…    def __init__ (self):
…        self.age = Student.default_age    # instance variable

				

Note that in the previous example, we had to use Student.default_age instead of using only default_age because the global namespace for a method is the module in which it was defined—not the class namespace.

The next example creates an instance variable that has the same name of the class variable.

					
>>> class Student:
…     default_age = 20                 # class variable
…     def __init__ (self, age):
…         self.default_age = age       # instance variable

				

Suppose that you have the following code stored in a file called c:\ python\ studentfile.py. This code defines three different variables named default_age (at lines 2, 4, and 9).

					
1: class Student:
2:     default_age = 20               # base class variable
3:     def __init__(self, age):
4:         self.default_age = age     # base class instance variable
5:
6: class Newstudent(Student):
7:     "New student class"
8:     def __init__(self, age=20):
9:         self.default_age = age     # instance variable

				

The following code imports the previous module. Which variable is being used by the instance call at line 5?

					
1: >>> import sys
2: >>> sys.path = sys.path + ['c:\ \ python']
3: >>> import studentfile
4: >>> Joao = studentfile.Newstudent(15)
5: >>> Joao.default_age
6: 15

				

Tip

In order for Python to find your modules, the directory where you save them must be an entry of the sys.path list.



The answer is the instance variable of the newstudent class (line 9 from the first listing). In cases like this, the search order is defined as

  1. instance variables

  2. class variables

  3. base classes variables—note that the search order for base classes makes the deepest-level classes used first

    							
    >>> Renata = studentfile.newstudent()
    >>> print Renata.default_age
    20
    
    						

The following variation is slightly different than the previous code. This example shows what you need to do to make the class Newstudent call the superclass's __init__ method.

					
6: class Newstudent(Student):
7:     "New student class"
8:     def __init__(self):
9:         Student.__init__(self, Student.default_age)

				

Note that we are calling the __init__ method of the Student class (the superclass). The class constant Student.default_age is also used in this example. It is important to say that when calling unbound methods (methods that are not tied to an instance) like this one, you must explicitly say that the first argument is self.

					
1: >>> Joao = studentfile.Newstudent()
2: >>> Joao.default_age
3: 20

				

Attributes of a Class

Next, I list the attributes that classes expose to programmers.

classname.__dict__—  This attribute contains the class namespace dictionary.

								
>>> studentfile.newstudent.__dict__
{ '__init__': <function __init__ at 799e90>, '__doc__': 'New student
 class', '__module__': 'studentfile'}

							

classname.__doc__—  This one returns the documentation string of the class.

								
>>> studentfile.newstudent.__doc__
'New student class'

							

classname.__name__—  This attribute returns the class name.

								
>>> studentfile.newstudent.__name__
'newstudent'

							

classname.__module__—  This one provides the module name that contains the class.

								
>>> studentfile.newstudent.__module__
'studentfile'

							

classname.__bases__—  This is a tuple containing the names of the base classes.

								
>>> studentfile.newstudent.__bases__
(<class studentfile.student at 799e00>,)

							

The Python Class Browser

The pyclbr module offers you the possibility of browsing all the information about classes that is stored in a specific module.

readmodule()

This function reads the module and returns a dictionary in the format { classname:classinfo}, where classinfo is an instance object of the class.

basic syntax: variable = pyclbr.readmodule(module)

							
>>> import pyclbr
>>> moduletobrowse = pyclbr.readmodule("profile")
>>> for classname, classinfo in moduletobrowse.items():
…     print "Class name: %s" % classname
…
Class name: HotProfile
Class name: OldProfile
Class name: Profile

						

or, if you use our student example

							
>>> import pyclbr
>>> moduletobrowse = pyclbr.readmodule("studentfile")
>>> for classname, classinfo in moduletobrowse.items():
…     print "Class name: %s" % classname
…
Class name: student
Class name: newstudent

						

If you need to go deeper than that, you can look at the classinfo object.

Python Instances

Each instance defines its own namespace of data, and it inherits behavior from the class (and possible base classes) that have originated it.

In order to create a new instance of a class, you just need to say

						
newinstance = classname()

					

Suppose that you have a Person class like this

						
class Person:
    def __init__(self, name):
        self.name = name
        self.family = []
    def addmember(self, member):
        self.family.append(member)

					

For example, if you want to create a new instance of the chef class, you must type:

						
>>> anthony =  Person()

					

You can also pass arguments to the __init__ function of the class. These arguments can be used to set the initial values of an object. Let's see how it works.

						
>>> anthony = Person("anthony")

					

To call the methods of a class, you have to use the dot notation:

						
>>> anthony.addmember("son")

					

You also need to use the dot notation to have access to variables (attributes) of each instance.

						
>>> anthony.family
["son"]

					

An interesting detail about Python object attributes is that they don't need to be declared inside the class before they get used because they can be created dynamically.

						
>>> class DummyClass:
…     pass
…
>>> colors = DummyClass()
>>> color.alarm = "red"

					

The next example dynamically creates multiple attributes for the colors instance.

						
>>> class record:
…     def __init__(self, **args):
…         self.__dict__.update(args)
…
>>> colors = record(alarm="red", normal="green")
>>> colors.normal
'green'

					
isinstance() and issubclass()

The built-in functions isinstance() and issubclass() are always available without the need for importing any module because they are part of the __builtin__ module.

isinstance()

This function tests whether an object is an instance of a class. It returns 1 if the object is an instance. Otherwise, it returns 0. Note that this function handles subclass relationships as well—for instance, isinstance(subclassinstance, superclass) returns true.

basic syntax: isinstance(instance_object, class_object)

								
>>> class a:
…    pass
…
>>> inst = a()
>>> isinstance(inst,a)
1

							

As you can see next, you can also use this function to identify the object's type. Note however, that this is behavior that works for non–instance objects. Floats and ints act quite differently from Python class instances (for instance, there is no way to subclass types.IntType).

								
>>> import types
>>> isinstance(3, types.IntType)
1
>>> isinstance(3, types.FloatType)
0

							
issubclass()

This function returns 1 if the class object classobj1 is a subclass (derived class) of the class object classobj2.

basic syntax: issubclass(classobj1, classobj2)

								
>>> class a:
…    pass
…
>>> class b(a):
…     pass
…
>>> issubclass(a,b)
1

							
Instance Attributes

obj.__dict__—This is the dictionary that contains all the attributes defined for the obj instance.

									
>>> colors.__dict__
{ 'alert': 'yellow', 'alarm': 'red', 'norma': 'green'}

								

obj.__class__—It shows the class that has created the obj instance.

									
>>> colors.__class__
<class __main__.record at 7883a0>

								

To get just the name of the class, use

									
>>> colors.__class__.__name__
'record'

								

obj.__methods__—This attribute is a list of all supported methods of the obj instance. Note that this attribute is available for lists and dictionaries, which are not class instances.

									
>>> a=[1,2]
>>> a.__methods__
['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove','reverse',
 'sort']

>>> b={ 1:''}
>>> b.__methods__
['clear', 'copy', 'get', 'has_key', 'items', 'keys', 'update', 'values']

								


Last updated on 1/30/2002
Python Developer's Handbook, © 2002 Sams Publishing

< BACKMake Note | BookmarkCONTINUE >

Index terms contained in this section

accessing
     variables
            instances
arguments
      self
attributes
      classname.__bases
      classname.__dict
      classname.__doc
      classname.__module
      classname.__name
      obj.__class__
      obj.__dict__
      obj.__methods__
browsing
      classes
calling
     methods
            classes
class instances
      creating
class keyword 2nd
class statements
classes 2nd 3rd 4th 5th 6th
classname.__bases attribute
classname.__dict attribute
classname.__doc attribute
classname.__module attribute
classname.__name attribute
constants
      classes
creating
      class instances
def keyword
definitions
      classes
functions
      isinstance()
      issubclass()
instances 2nd 3rd 4th 5th 6th
      accessing variables
     classes
            creating
isinstance() function
issubclass() function
keywords
      class 2nd
      def
methods
      classes
            calling
modules
     pyclbr
            browsing classes
obj.__class__ attribute
obj.__dict__ attribute
obj.__methods__ attribute
object-oriented programming (OOP)
      Python classes and instances 2nd 3rd 4th 5th 6th
programming
     object-oriented (OOP)
            Python classes and instances 2nd 3rd 4th 5th 6th
pyclbr module
      browsing classes
self argument
statements
      class
syntax
     functions
            isinstance()
            issubclass()
            readmodule()
variables
     accessing
            instances
      classes 2nd

© 2002, O'Reilly & Associates, Inc.