setattr and getattr, when to use?

Jason Scheirer jason.scheirer at gmail.com
Sat Aug 23 01:17:01 EDT 2008


On Aug 22, 8:50 pm, maestro <notnorweg... at yahoo.se> wrote:
> Why are these functions there? Is it somehow more idiomatic to use
> than to do obj.field ?
> Is there something you can with them that you can't by obj.field
> reference?

You can generate them dynamically from strings. In some cases you
don't know until runtime what attributes you want to pull:

def show_insides(obj):
  for attr in dir(obj):
    print "Attribute %r: %r" % (attr, getattr(obj, attr))

class hello(object):
   a = 1
   b = 2

class goodbye(object):
   c = 1
   d = 500


print show_insides(hello)
(...15 builtins...)
Attribute 'a': 1
Attribute 'b': 2

print show_insides(goodbye)
(...15 builtins...)
Attribute 'c': 1
Attribute 'd': 500

In this case, you can see that we pull the attributes of an object
using dir(), which yields a list of strings, then pull each attribute
we discover.



More information about the Python-list mailing list