ASPN ActiveState Programmer Network
  ActiveState
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups | Web Services
SEARCH
advanced | search help

Reference
ActivePython 2.4
Python Documentation
Language Reference
3. Data model
3.3 Special method names
3.3.3 Customizing class creation

MyASPN >> Reference >> ActivePython 2.4 >> Python Documentation >> Language Reference >> 3. Data model >> 3.3 Special method names
ActivePython 2.4 documentation


3.3.3 Customizing class creation

By default, new-style classes are constructed using type(). A class definition is read into a separate namespace and the value of class name is bound to the result of type(name, bases, dict).

When the class definition is read, if __metaclass__ is defined then the callable assigned to it will be called instead of type(). The allows classes or functions to be written which monitor or alter the class creation process:

  • Modifying the class dictionary prior to the class being created.
  • Returning an instance of another class - essentially performing the role of a factory function.

__metaclass__
This variable can be any callable accepting arguments for name, bases, and dict. Upon class creation, the callable is used instead of the built-in type(). New in version 2.2.

The appropriate metaclass is determined by the following precedence rules:

  • If dict['__metaclass__'] exists, it is used.

  • Otherwise, if there is at least one base class, its metaclass is used (this looks for a __class__ attribute first and if not found, uses its type).

  • Otherwise, if a global variable named __metaclass__ exists, it is used.

  • Otherwise, the old-style, classic metaclass (types.ClassType) is used.

The potential uses for metaclasses are boundless. Some ideas that have been explored including logging, interface checking, automatic delegation, automatic property creation, proxies, frameworks, and automatic resource locking/synchronization.

See About this document... for information on suggesting changes.

Privacy Policy | Email Opt-out | Feedback | Syndication
© ActiveState 2004 All rights reserved