Data Structures and Algorithms with Object-Oriented Design Patterns in Python
next up previous index

Nested Classes

In Python it is possible to define one class inside another. A class defined inside another one is called a nested class .

Consider the following Python code fragment:

class A(object):

    def __init__(self):
	self.y = 0

    class B(object):

	def __init__(self):
	    self.x = 0

	def f(self):
	    pass
This fragment defines the class A which contains the nested class B.

A nested class behaves like any ``outer'' (un-nested) class. It may contain methods and instance attributes, and it may be instantiated like this:

obj = A.B()
This statement creates an new instance of the nested class B. Given such an instance, we can invoke the f method in the usual way:
obj.f()

Note, it is not necessarily the case that an instance of the outer class A exists even when we have created an instance of the inner class. Similarly, instantiating the outer class A does not create any instances of the inner class B.

The methods of a nested class may access the instance attributes of the nested class instance but not of any outer class instance Thus, method f can access the instance attribute x, but it cannot access the instance attribute y.


next up previous index

Bruno Copyright © 2003, 2004 by Bruno R. Preiss, P.Eng. All rights reserved.