Adding attributes stored in a list to a class dynamically.

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Mon Sep 3 05:34:31 EDT 2007


Brian Munroe a écrit :
> On Sep 2, 3:33 pm, Steven D'Aprano <st... at REMOVE-THIS-
> cybersource.com.au> wrote:
> 
>> In a nutshell, like all double-underscore methods, __setattr__ are for
>> overriding behaviour in your own classes. With very few exceptions, you
>> shouldn't need to directly call double-underscore methods (although you
>> often may _write_ double-underscore methods).
>>
> 
> I think I understand.  You are saying that if I wanted to override the
> normal behavior when doing something like
> 
>     p1.firstName = "Brian"
> 
> then I'd override __setattr__()?

That's one possible solution. Another one is to use a property object or 
a custom descriptor (you should find relevant documentation on python.org).

> But if I am doing something like creating dynamic attributes, the more
> 'correct' way is to use setattr?  Even though they both appear to do
> the same thing, the more Pythonic way is to never directly call magic
> methods (if you can help it)?

Mainly, yes.



More information about the Python-list mailing list