[Tutor] setattr vs __setattr__
Rasjid Wilcox
rasjidw at gmail.com
Mon Sep 6 13:03:30 CEST 2010
On 6 September 2010 19:55, Hugo Arts <hugo.yoshi at gmail.com> wrote:
> 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.
Sorry, yes, a.__setattr__('foo', 'bar') is what I meant. I'm actually
iterating over a number of attributes, so AFASK the first form is not
an option. I've been using
for attr_name in name_list:
setattr(a, attr_name, getattr(b, attr_name))
to copy the attributes from one type of class to another, and it is
not quite as readable as I would like. Actually, I've just thought
that the best option would be to make both classes dictionary like
objects with automatic translation between a['foo'] and a.foo.
Sqlalchemy uses that for its query result objects with good effect.
Cheers,
Rasjid.
More information about the Tutor
mailing list