How to find the classname of an object? (was Python Documentation)

Bengt Richter bokr at oz.net
Fri May 13 17:03:04 EDT 2005


On 13 May 2005 09:37:07 -0700, "Matt" <matthew_shomphe at countrywide.com> wrote:

>
>Christopher J. Bottaro wrote:
>> Christopher J. Bottaro wrote:
>>
>> > Bengt Richter wrote:
>> >
>> >>  >>> type(obj)
>> >>  <class '__main__.A'>
>> >>  >>> type(obj).mro()
>> >>  [<class '__main__.A'>, <class '__main__.B1'>, <class
>'__main__.B2'>,
>> >>  [<class '__main__.C'>, <type 'object'>]
>> >>  >>> tuple(x.__name__ for x in type(obj).mro())
>> >>  ('A', 'B1', 'B2', 'C', 'object')
>> >
>> > Wow awesome, thats exactly what I was looking for.
>>
>> Wait a sec...why doesn't the following code work then?
>>
Well, I suspect it actually does work, technically, but I suspect
it hints at the way old-style classes were implemented in the environment
of the new, rather than giving you what you might expect.

>> class FWException(Exception): pass
>> class FWA(FWException): pass
>> class FWB(FWA): pass
>> class FWC(FWB): pass
>> e = FWC()
>> print [ cl.__name__ for cl in type(e).mro() ]
>>
>> Thanks again.
>> --C
>
>
>Is it because you need to inherit from "object"?
>
>class FWException(Exception, object): pass # note "object"
>class FWA(FWException): pass
>class FWB(FWA): pass
>class FWC(FWB): pass
>e = FWC()
>print [ cl.__name__ for cl in type(e).mro()]
>
>#prints ['FWC', 'FWB', 'FWA', 'FWException', 'Exception', 'object']
>
I'm afraid inheriting explicitly from object will make the exception unraisable.
Exceptions are still based on "classic" classes for some reason that
I don't know enough about to explain.

So if you were hoping to use .mro() with old-style classes to see the
old-style inheritance chain, as opposed to new-style inheritance that
underlies access to special entities involved in the implementation of the old, sorry ;-/

At least that's the way it looks to me, without digging in that part of the code.

Regards,
Bengt Richter



More information about the Python-list mailing list