How to iterate over an instance object's data attributes in Python
To list the attributes of a Python instance object, I could use the built-in dir()
function, however, this will return the instance object's methods as well data attributes. To get just the data attributes, I can use the instance object's __dict__
attribute:
class A(object):
def __init__(self):
self.myinstatt1 = 'one'
self.myinstatt2 = 'two'
def mymethod(self):
pass
a = A()
for attr, value in a.__dict__.iteritems():
print attr, value
myinstatt2 two myinstatt1 one
Comments
I just tried _ _ dict _ _ (take out spaces) on a Django entity and got an error "'str' object has no attribute '_meta'". Guess I'll keep looking for a way to iterate database fields only for my Django entity?
-- Trindaz/Python on Fedang
Thanks for this useful example you provided. I always find seeing simple examples to be the easiest way to learn.
Nice example.
Suppose you have a class with class variables, e.g.
class Foo(object):
one = 1
letter = "a"
How do you iterate over 'one' and 'letter'?
There is a function that exposes the __dict__
method. It's equivalent, but probably more pythonic. The vars built-in function http://docs.python.org/library/functions.html#vars
for k, v in vars(a).items():
print k, v
myinstatt2 two
myinstatt1 one
When I use the vars(a) method illustrated by Z on a generic namespace, I get the data elements, but I also get a "trash" element akin to:
<__main__.Fragment instance at 0x009DE56C>
Is there any simple way to suppress this?
Find myself referencing this blog quite a bit. Thank you for the shares over the years, like to think I'll get back into the habit of writing to my bog sometime and think the regular examples here will help move that forward.
Hi Alvin, Thanks! That would be great if you started writing more blog posts. There are a lot of people that have a lot of information that I wish would write blog posts.
Z: Agree vars() is more pythonic. I just learned about that recently. Thanks for the tip!
I always find myself forgetting this idiom, thanks for making it easy to find again.
Hey I really appreciate your blog. I have found no other place that answers so many of my Python questions so quickly. Just want to say thank you and keep it up.
Merry Christmas,
-Paxwell
This article was the last stop on a very long search for me. Thank you so much.
Many thanks for this concise and helpful post - had no idea I could get a free dict for my custom class. Lovely!