[Tutor] Getting an object's attributes

Steven D'Aprano steve at pearwood.info
Sat Jun 26 12:17:48 CEST 2010


On Sat, 26 Jun 2010 06:39:29 pm mhw at doctors.net.uk wrote:
> Dear Tutors,
>
> 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
>
> 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.

If you know they are called name and age, just access them like you did 
above:

Obj1.name
Obj1.age


If you don't know they are called name and age, then how do you expect 
Python to know which of the many attributes and methods are the ones 
you want?

Before you start writing your own filters, you should check out the 
inspect module, which already has most of that functionality 
ready-made.

There's no general way to ask "which attributes were added dynamically?" 
because all of them are. The difference is that some of them are added 
dynamically when the class is created, some are added dynamically when 
the instance is initialised, and some are added dynamically later. But 
they're all added dynamically. Python doesn't track when attributes are 
added because, in general, it's an unimportant difference.


-- 
Steven D'Aprano


More information about the Tutor mailing list