Getting Inside the Factory How Class and Instance Namespaces Interact

A class and an instance each have a namespace, which is storage for the names of objects that Python knows about. When you create an instance of a class, the instance has its own namespace, but it also shares the class's namespace.

Whenever Python encounters a name that's part of an instance, it looks for the value first in the instance's namespace. If it can't find the value there, it looks in the class's namespace.

Tip Function namespaces and global namespaces interact in similar ways. See Chapter 11.

So anything that you do to the class namespace (such as changing an attribute of the class) is also reflected in the instance—except when the instance has already overridden that value from the class namespace. The next section shows how it works.

Was this article helpful?

0 0

Post a comment