setattr and getattr, when to use?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Aug 23 04:16:59 EDT 2008


On Fri, 22 Aug 2008 20:50:17 -0700, maestro wrote:

> Why are these functions there? Is it somehow more idiomatic to use than
> to do obj.field ?


Heavens no!!! Using setattr and getattr is *less* idiomatic.


> Is there something you can with them that you can't by obj.field
> reference?

Absolutely. Consider:

class Foo(object):
    pass

foo = Foo()
setattr(foo, "x y", 1)
print getattr(foo, "x y")

That's probably an abuse of setattr/getattr, but there are times where 
you might not know the name of the attribute until runtime, so you can't 
write foo.attr since you don't know what to write in place of attr. 
That's where setattr and getattr (as well as delattr and hasattr) come 
into play.



-- 
Steven



More information about the Python-list mailing list