setattr and getattr, when to use?

Jason Scheirer jason.scheirer at gmail.com
Sat Aug 23 07:18:29 CEST 2008


On Aug 22, 10:17 pm, Jason Scheirer <jason.schei... at gmail.com> wrote:
> 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.

Might I add: avoid doing this if you don't have to. obj.field is the
way to go about getting your object attributes 95% of the time. The 5%
of your time when you are doing metaprogramming or other abuses of the
object system are when you use get/setattr.



More information about the Python-list mailing list