Saltycrane logo

SaltyCrane Blog

Notes on Python, Django, and web development on Ubuntu Linux

    

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
Results:
myinstatt2 two
myinstatt1 one

4 Comments — feed icon Comments feed for this post


#1 Dave commented on 2010-07-30:

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


#2 John commented on 2011-01-19:

Thanks for this useful example you provided. I always find seeing simple examples to be the easiest way to learn.


#3 dan commented on 2011-09-18:

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'?


#4 Z commented on 2012-02-08:

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

Post a comment

Required
Required, but not displayed
Optional

Format using Markdown. (No HTML.)
  • Code blocks: prefix each line by at least 4 spaces or 1 tab (and a blank line before and after)
  • Code span: surround with backticks
  • Blockquotes: prefix lines to be quoted with >
  • Links: <URL>
  • Links w/ description: [description](URL)
Created with Django | Hosted by Linode