CONSTRUCT - Adding Functionality to the Overall System

Georg Brandl g.brandl-nospam at gmx.net
Tue Sep 19 02:22:41 EDT 2006


Damjan wrote:
>>> I understand that I can use __metaclass__ to create a class which
>>> modifies the behaviour of another class.
>>> 
>>> How can I add this metaclass to *all* classes in the system?
>>> 
>>> (In ruby I would alter the "Class" class)
>> 
>> You'd have to set
>> 
>> __metaclass__ = whatever
>> 
>> at the top of each module whose classes are to get the new behavior.
> 
> I think '__metaclass__ = whatever' affects only the creation of classes that
> would otherwise be old-style classes?

Wrong.

If you set __metaclass__ = type, every class in that module will be new-style.

If you set __metaclass__ = MyClass, and MyClass inherits from <type>, every
class in that module will be new-style and have MyClass as a metaclass.

The usual way to create new-style classes, inheriting from object or another
new-style class, works because if no __metaclass__ is defined, the first
base class's class is taken as the metaclass.

Georg



More information about the Python-list mailing list