Online Book Reader

Home Category

Learning Python - Mark Lutz [383]

By Root 1814 0
into existence when assigned, and not before. Normally we create instance attributes by assigning them in class __init__ constructor methods, but this isn’t the only option.

Finally, as we learned in Chapter 17, it’s also possible for a function to change names outside itself, with global and (in Python 3.0) nonlocal statements—these statements provide write access, but also modify assignment’s namespace binding rules:

X = 11 # Global in module

def g1():

print(X) # Reference global in module

def g2():

global X

X = 22 # Change global in module

def h1():

X = 33 # Local in function

def nested():

print(X) # Reference local in enclosing scope

def h2():

X = 33 # Local in function

def nested():

nonlocal X # Python 3.0 statement

X = 44 # Change local in enclosing scope

Of course, you generally shouldn’t use the same name for every variable in your script—but as this example demonstrates, even if you do, Python’s namespaces will work to keep names used in one context from accidentally clashing with those used in another.

Namespace Dictionaries

In Chapter 22, we learned that module namespaces are actually implemented as dictionaries and exposed with the built-in __dict__ attribute. The same holds for class and instance objects: attribute qualification is really a dictionary indexing operation internally, and attribute inheritance is just a matter of searching linked dictionaries. In fact, instance and class objects are mostly just dictionaries with links inside Python. Python exposes these dictionaries, as well as the links between them, for use in advanced roles (e.g., for coding tools).

To help you understand how attributes work internally, let’s work through an interactive session that traces the way namespace dictionaries grow when classes are involved. We saw a simpler version of this type of code in Chapter 26, but now that we know more about methods and superclasses, let’s embellish it here. First, let’s define a superclass and a subclass with methods that will store data in their instances:

>>> class super:

... def hello(self):

... self.data1 = 'spam'

...

>>> class sub(super):

... def hola(self):

... self.data2 = 'eggs'

...

When we make an instance of the subclass, the instance starts out with an empty namespace dictionary, but it has links back to the class for the inheritance search to follow. In fact, the inheritance tree is explicitly available in special attributes, which you can inspect. Instances have a __class__ attribute that links to their class, and classes have a __bases__ attribute that is a tuple containing links to higher superclasses (I’m running this on Python 3.0; name formats and some internal attributes vary slightly in 2.6):

>>> X = sub()

>>> X.__dict__ # Instance namespace dict

{}

>>> X.__class__ # Class of instance

>>> sub.__bases__ # Superclasses of class

(,)

>>> super.__bases__ # () empty tuple in Python 2.6

(,)

As classes assign to self attributes, they populate the instance objects—that is, attributes wind up in the instances’ attribute namespace dictionaries, not in the classes’. An instance object’s namespace records data that can vary from instance to instance, and self is a hook into that namespace:

>>> Y = sub()

>>> X.hello()

>>> X.__dict__

{'data1': 'spam'}

>>> X.hola()

>>> X.__dict__

{'data1': 'spam', 'data2': 'eggs'}

>>> sub.__dict__.keys()

['__module__', '__doc__', 'hola']

>>> super.__dict__.keys()

['__dict__', '__module__', '__weakref__', 'hello', '__doc__']

>>> Y.__dict__

{}

Notice the extra underscore names in the class dictionaries; Python sets these automatically. Most are not used in typical programs, but there are tools that use some of them (e.g., __doc__ holds the docstrings discussed in Chapter 15).

Also, observe that Y, a second instance made at the start of this series, still has an empty namespace dictionary at the end, even though X’s dictionary has been populated by assignments in methods. Again, each instance has an independent

Return Main Page Previous Page Next Page

®Online Book Reader