How to list the superclassesof an object

Alex Martelli aleax at aleax.it
Wed Nov 5 19:29:50 CET 2003


Fernando Rodriguez wrote:

> On Wed, 05 Nov 2003 16:17:11 GMT, Alex Martelli <aleax at aleax.it> wrote:
> 
> 
>>>>> x.__class__.__bases__
>>(<class __main__.A at 0x402db41c>, <class __main__.B at 0x402db44c>)
> 
> I didn't know the existence of the __bases__ attribute, and it doesn't
> show
> with dir().  How can I get a list of ALL the attributes of an object?

try hasattr(x, somest) for all identifier strings somest (up to whatever
length you're comfortable with).  Nothing stops an object from 'inventing'
attributes on the fly when queried about them, e.g:

class allem(object):
    def __getattr__(self, name): return name
x=allem()

now x 'has' ANY attribute you can name, in the sense it will give a
value for x.supercalifragilisticexpialidocious and so on.  How else
save by exhaustive search could you find this out...?

> I thought that dir()  listed every attribute.... O:-)

No, it can't take days every time you call it;-)


>>You may need a recursive walk up the (DA) graph if you also want
>>bases of bases, etc, among 'superclasses'; alternatively, but
>>ONLY for newstyle classes (recommended anyway for many reasons):
> 
> I haven't used python in a while and all my classes are 'old style'. I'd
> like to get up to date. Where can I find info about the differences /
> advantages of
> these new classes?  Is it safe to convert all my previous classes to new
> ones, and how can I do it? O:-)

I suggest peeking at the OO chapter of Python in a Nutshell -- I
think I cover the issues decently (do it for free by subscribing
at safari.oreilly.com and canceling before 14 days, since the
first 2 weeks are free).


Alex





More information about the Python-list mailing list