Classic vs New-style classes...

Aahz aahz at pythoncraft.com
Sat Jun 21 05:27:33 CEST 2003


In article <mailman.1056162937.4237.python-list at python.org>,
Martin Chilvers <martin_chilvers at gmx.net> wrote:
>First of all, I should have asked a better question ;^)
>Second, I think I've answered it myself!
>
>> I've searched the archives and docs for an answer to this one, but I'm
>> still stuck...
>>
>> >>> class Foo(object)
>> ... pass
>> ...
>> >>> Foo.__dict__['bar'] = lambda self, x: x * 2
>> Traceback (most recent call last):
>> File "<stdin>", line 1, in ?
>> TypeError: object does not support item assignment
>> >>> type(Foo.__dict__)
>> <type 'dict-proxy'>
>
>What I really wanted was this:-
>
>	def addToClass(klass, name, value):
>    	    exec('klass.%s = value' % name)
>
>With classic classes, it can be written as:-
>
>	def addToClass(klass, name, value):
>    	    klass.__dict__[name] = value
>
>So now my question is... is this the cleanest way with new-style classes?

Try setattr() instead.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

Usenet is not a democracy.  It is a weird cross between an anarchy and a
dictatorship.  




More information about the Python-list mailing list