Struct usages in Python
Arnaud Delobelle
arnodel at googlemail.com
Wed May 28 13:50:01 EDT 2008
"Alex Gusarov" <alex.m.gusarov at gmail.com> writes:
>> class Event(object):
>>
>> Always subclass object, unless you have a very compelling reason not to,
>> or you are subclassing something else.
>>
>
> I've thought that if I write
>
> class Event:
> pass
>
> , it'll be subclass of object too, I was wrong?
You are wrong for Python 2.X, but right for Python 3 where old-style
classes are gone for good.
What you define with the statement
class Event: pass
is an 'old-style' class. Witness:
>>> class Event: pass
...
>>> class NewEvent(object): pass
...
>>> type(Event)
<type 'classobj'>
>>> type(NewEvent)
<type 'type'>
>>> type(Event())
<type 'instance'>
del>>> type(NewEvent())
<class '__main__.NewEvent'>
All old-style classes are actually objects of type 'classobj' (they
all have the same type!), all their instances are all of type 'instance'.
>>> type(FooBar) == type(Event)
True
>>> type(FooBar()) == type(Event())
True
Whereas instances of new-style classes are of type their class:
>>> class NewFooBar(object): pass
...
>>> type(NewFooBar) == type(NewEvent)
True
>>> type(NewFooBar()) == type(NewEvent())
False
However, in python 2.X (X > 2?), you can force all classes to of a
certain type by setting the global variable '__metaclass__'. So:
>>> type(Event) # Event is an old-style class
<type 'classobj'>
>>> __metaclass__ = type
>>> class Event: pass
...
>>> type(Event) # Now Event is new-style!
<type 'type'>
HTH
--
Arnaud
More information about the Python-list
mailing list