[Tutor] setattr vs __setattr__

Hugo Arts hugo.yoshi at gmail.com
Mon Sep 6 11:55:02 CEST 2010


On Mon, Sep 6, 2010 at 9:27 AM, Rasjid Wilcox <rasjidw at gmail.com> wrote:
> Hi all,
>
> Suppose we have
>
> class A(object):
>    pass
>
> a = A()
>
> Is there any difference between
>
> setattr(a, 'foo', 'bar)
>
> and
>
> a.__setattr__['foo'] = 'bar'
>

Did you mean a.__setattr__('foo', 'bar')? That's the same thing,
though you'd generally use a.foo = 'bar' or setattr(a, 'foo', 'bar'),
in that order of preference.

If you meant a.__dict__['foo'] = 'bar', that may or may not be the
same thing depending on the class. It works for instances of object,
but fails for any class that defines __slots__, for example.  I'd
generally recommend you don't do it. Use setattr instead.

Hugo


More information about the Tutor mailing list