[Tutor] setattr vs __setattr__

Steven D'Aprano steve at pearwood.info
Tue Sep 7 00:55:28 CEST 2010

On Mon, 6 Sep 2010 09:03:30 pm Rasjid Wilcox wrote:
> 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.

The one-liner in the for loop is very concise. The problem is that 
concise is often the opposite of readable. So make it less concise:

for name in name_list:
    obj = getattr(b, name)
    setattr(a, name, obj)

Does that help?

Another alternative, depending on the class, *might* be this:


although that's a hack, and like all hacks, may not do what you expect 
for all classes.

> 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.

How does that help you copy from one class to another? As I see it, it 
just adds more noise to the class.

Steven D'Aprano

More information about the Tutor mailing list