Feature request: String-inferred names

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Tue Dec 1 09:38:01 EST 2009


On Mon, 30 Nov 2009 18:55:46 -0800, The Music Guy wrote:

> Lie Ryan, I think I see what you're saying about using __dict__ to add
> members to a class, but it's not quite the same. __dict__ is only for
> attributes, NOT properties, methods, etc. which all come from the class
> of an object rather than the object's __dict__. 

Almost but not quite.

It's just special double-underscore methods like __init__ __add__ etc 
that have to be in the class rather than the instance. (To be precise, 
you can add such a method to the instance, but it won't be called 
automatically.) Likewise staticmethods and classmethods won't work 
correctly unless they are in the class. But ordinary methods work fine: 
the only tricky bit is creating them in the first place.

>>> class K(object):
...     pass
...
>>> k = K()
>>> import types
>>> k.method = types.MethodType(lambda self: "I am %s" % self, k)
>>> k.method()
'I am <__main__.K object at 0xb7cc7d4c>'



-- 
Steven



More information about the Python-list mailing list