What are new-style classes?

Reinhold Birkenfeld reinhold-birkenfeld-nospam at wolke7.net
Tue Aug 30 17:09:37 EDT 2005


Colin J. Williams wrote:

>>>>I recently heard about 'new-style classes'. I am very sorry if this
>>>>sounds like a newbie question, but what are they? I checked the Python
>>>>Manual but did not find anything conclusive. Could someone please
>>>>enlighten me? Thanks!
>>>
>>>"New style" classes are becoming the standard in Python, and must
>>>always be declared as a subclass of a new style class, including built-in
>>>classes.
>> 
>> 
>> [Warning, advanced stuff ahead!]
>> 
>> That's not entirely true. New-style classes need not be derived from a new-
>> style class, they need to use the metaclass "type" or a derived.
>> 
>> So you can also declare a new-style class as
>> 
>> class new_class:
>>     __metaclass__ = type
>> 
>> Or, if you want to switch a whole module with many classes to new-style, just set a
>> 
>> __metaclass__ = type
>> 
>> globally.
>> 
> What are the pros and cons of the alternate approach?

The customary way is to use "class new_class(object):". There's no advantage in using
__metaclass__ except that you can set it globally for all classes in that module
(which can be confusing on its own).

My comment mostly referred to "new-style classes must be declared as a subclass of
a new-style class", which is not true.

Reinhold



More information about the Python-list mailing list