[Tutor] Getting an object's attributes

mhw at doctors.net.uk mhw at doctors.net.uk
Sun Jun 27 00:03:29 CEST 2010

Apol. For TP:

This is perfect - thanks.
Sent from my BlackBerry® wireless device

-----Original Message-----
From: Evert Rol <evert.rol at gmail.com>
Date: Sat, 26 Jun 2010 11:13:16 
To: <mhw at doctors.net.uk>
Cc: Python tutor<Tutor at python.org>
Subject: Re: [Tutor] Getting an object's attributes

> I have an object to which I dynamically add attributes. My question is how I can inspect and display them at run-time?
> Class a():
>    pass
> Obj1 = a()
> Obj1.name = "Bob"
> Obj1.age = 45

First off, a few suggestions:
- you probably mean 'class', not 'Class' (sorry, but it's just that correct actual code helps: copy-paste from the Python prompt when you can. If you have a text-editor in your mail program that capitalises things, be careful when pasting code).
- use capitalisation (or CamelCase) for class names, lowercase for instances: class A, obj1 = A(). This is the usual Python convention.
- I would use new-style classes, ie, inherit from object:
>>> class A(object):
...   pass
>>> obj1 = A()

> dir(a) returns a tuple which contains name and age, but also other things (includings methods, etc.) I could filter this tuple (checking for callable(), etc.)  but I just wondered if there was an existing way of getting just name and age.

Normally, you know which attributes you want to access, so you wouldn't have this problem. Better yet, you wrap things in a try-except clause and see if that works:
>>> try:
...     obj1.name
... except AttributeError:
...     print "not there"
not there

But for this case, when using new-style classes, obj1.__dict__ can help you (or obj1.__dict__.keys() ). 
>>> obj1.name = "Bob"
>>> obj1.age = 45
>>> obj1.__dict__
{'age': 45, 'name': 'Bob'}

Or, perhaps somewhat silly: set(dir(obj1)) - set(dir(A)).
>>> set(dir(obj1)) - set(dir(A))
set(['age', 'name'])

but I wouldn't recommend that.

See eg http://docs.python.org/library/stdtypes.html#special-attributes

More information about the Tutor mailing list