[Tutor] python instances and type

Kent Johnson kent37 at tds.net
Mon Apr 16 12:27:33 CEST 2007


Adam Pridgen wrote:

> x = foo_1()
> x.data = "boring"
> print type(x), type(x).mro()
> <class 'foo_1'> [<class 'foo_1'>]

> print type(bar), type(bar).mro()
> <type 'instance'> [<type 'instance'>, <type 'object'>]

As Andre has pointed out, this is a difference between new- and 
old-style classes, not an artifact of the way you are using the classes.

The type and the class of an instance of an old-style class are not the 
same. To find out the class of an old-style class instance, you should 
use the __class__ attribute:
In [1]: class foo_1: pass   # old-style class
    ...:
In [2]: class foo_2(object): pass   # new-style class
    ...:
In [3]: f1 = foo_1()
In [4]: type(f1)
Out[4]: <type 'instance'>
In [5]: f1.__class__
Out[5]: <class __main__.foo_1 at 0x1201090>

For instances of new-style classes, it's class and type are the same and 
__class__ and type() give the same result:
In [14]: f2=foo_2()
In [15]: f2.__class__
Out[15]: <class '__main__.foo_2'>
In [16]: type(f2)
Out[16]: <class '__main__.foo_2'>

If you want to know the base classes that will be searched for attribute 
access of an old-style class, use inspect.getmro(). This will work for 
new-style classes also.

In [19]: import inspect
In [22]: class foo_3(foo_1): pass
    ....:
In [23]: f3=foo_3()
In [24]: type(f3).mro()
Out[24]: [<type 'instance'>, <type 'object'>]
In [25]: inspect.getmro(f3.__class__)
Out[25]: (<class __main__.foo_3 at 0x1272c90>, <class __main__.foo_1 at 
0x1201090>)

Kent



More information about the Tutor mailing list