Constructing a decorated class

A decorated class construction is a nested set of several two-stage processes. Making class construction more complex is the way references are made to class methods. The references involve a multistep lookup. An object's class will define a Method Resolution Order (MRO). This defines how base classes are searched to locate an attribute or method name. The MRO works its way up the inheritance hierarchy; this is how a subclass name can override a name in a superclass. 

The outermost part of the nesting is processing the class statement as a whole. This has two stages: building the class, and applying the decorator functions. Within the class statement processing, the individual method definitions can also have decorations, and each of those is a two-stage process.

The first stage in class construction is the execution of the class statement. This stage involves the evaluation of the metaclass followed by the execution of the sequence of assignment and def statements within a class. Each def statement within the class expands to a nested two-stage function construction as described previously. Decorators can be applied to each method function as part of the process of building the class.

The second stage in class construction is to apply an overall class decorator to a class definition. Generally, this can add features. It's somewhat more common to add attributes rather than methods. While it is possible for decorators to add method functions, it can be hopelessly confusing for software maintainers to locate the source for a method injected by a decorator. These kinds of features need to be designed with considerable care.

The features inherited from the superclasses cannot be modified through decorators since they are resolved lazily by method resolution lookup. This leads to some important design considerations. We generally want to introduce methods and attributes through classes and mixin classes. We should limit ourselves to defining new attributes via decorators.

Here's a list of some of the attributes that are built for a class. A number of additional attributes are part of the metaclass; they are described in the following table:

__doc__

The class's documentation string, or none if undefined

__name__

The class name

__module__

The module name that the class was defined in

__dict__

The dictionary containing the class's namespace

__bases__

A tuple (possibly empty or a singleton) containing the base classes, in the order of their occurrence in the base class list; it is used to work out the method resolution order

__class__

The superclass of this class, often type

 

Some additional method functions that are part of a class include __subclasshook__, __reduce__, and __reduce_ex__, which are part of the interface for pickle.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset