Online Book Reader

Home Category

Learning Python - Mark Lutz [350]

By Root 1939 0
links to other dictionaries. If you know where to look, you can see this explicitly.

For example, the __dict__ attribute is the namespace dictionary for most class-based objects (some classes may also define attributes in __slots__, an advanced and seldom-used feature that we’ll study in Chapters 30 and 31). The following was run in Python 3.0; the order of names and set of __X__ internal names present can vary from release to release, but the names we assigned are present in all:

>>> rec.__dict__.keys()

['__module__', 'name', 'age', '__dict__', '__weakref__', '__doc__']

>>> list(x.__dict__.keys())

['name']

>>> list(y.__dict__.keys()) # list() not required in Python 2.6

[]

Here, the class’s namespace dictionary shows the name and age attributes we assigned to it, x has its own name, and y is still empty. Each instance has a link to its class for inheritance, though—it’s called __class__, if you want to inspect it:

>>> x.__class__

Classes also have a __bases__ attribute, which is a tuple of their superclasses:

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

(,)

These two attributes are how class trees are literally represented in memory by Python.

The main point to take away from this look under the hood is that Python’s class model is extremely dynamic. Classes and instances are just namespace objects, with attributes created on the fly by assignment. Those assignments usually happen within the class statements you code, but they can occur anywhere you have a reference to one of the objects in the tree.

Even methods, normally created by a def nested in a class, can be created completely independently of any class object. The following, for example, defines a simple function outside of any class that takes one argument:

>>> def upperName(self):

... return self.name.upper() # Still needs a self

There is nothing about a class here yet—it’s a simple function, and it can be called as such at this point, provided we pass in an object with a name attribute (the name self does not make this special in any way):

>>> upperName(x) # Call as a simple function

'SUE'

If we assign this simple function to an attribute of our class, though, it becomes a method, callable through any instance (as well as through the class name itself, as long as we pass in an instance manually):[61]

>>> rec.method = upperName

>>> x.method() # Run method to process x

'SUE'

>>> y.method() # Same, but pass y to self

'BOB'

>>> rec.method(x) # Can call through instance or class

'SUE'

Normally, classes are filled out by class statements, and instance attributes are created by assignments to self attributes in method functions. The point again, though, is that they don’t have to be; OOP in Python really is mostly about looking up attributes in linked namespace objects.

Classes Versus Dictionaries

Although the simple classes of the prior section are meant to illustrate class model basics, the techniques they employ can also be used for real work. For example, Chapter 8 showed how to use dictionaries to record properties of entities in our programs. It turns out that classes can serve this role, too—they package information like dictionaries, but can also bundle processing logic in the form of methods. For reference, here is the example for dictionary-based records we used earlier in the book:

>>> rec = {}

>>> rec['name'] = 'mel' # Dictionary-based record

>>> rec['age'] = 45

>>> rec['job'] = 'trainer/writer'

>>>

>>> print(rec['name'])

mel

This code emulates tools like records in other languages. As we just saw, though, there are also multiple ways to do the same with classes. Perhaps the simplest is this—trading keys for attributes:

>>> class rec: pass

...

>>> rec.name = 'mel' # Class-based record

>>> rec.age = 45

>>> rec.job = 'trainer/writer'

>>>

>>> print(rec.age)

40

This code has substantially less syntax than the dictionary equivalent. It uses an empty class statement to generate an empty namespace object. Once we make the empty class, we

Return Main Page Previous Page Next Page

®Online Book Reader