Classic vs New-style classes...

Martin Chilvers martin_chilvers at gmx.net
Fri Jun 20 22:35:45 EDT 2003


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?

Thanks for the previous responses,

Martin Chilvers
martin at enthought.com







More information about the Python-list mailing list