Is there an official way to add methods to an instance?
Bruno Desthuilliers
bruno.42.desthuilliers at websiteburo.invalid
Fri Apr 4 07:50:45 EDT 2008
Peter Otten a écrit :
(snip)
> Anyway, here is one more option to add too the zoo:
>
>>>> class A(object):
> ... def __init__(self, f, x):
> ... self._f = f
> ... self.x = x
> ... @property
> ... def f(self):
> ... return self._f.__get__(self)
> ... def __del__(self):
> ... print "deleting"
> ...
This is nice but requires that you know in advance how many methods
you're going to add and how they will be named (which is not a bad thing
in itself - on the contrary - but may not be what the OP is after), and
that you can add these methods at instanciation time.
A variant could be:
class A(object):
def __init__(self, x):
self.x = x
def __getattr__(self, name):
target = '_' + name
# avoids recursion
if hasattr(self, target):
func = getattr(self, target)
if hasattr(func, '__get__'):
return func.__get__(self, type(self))
# nothing found, bye...
raise AttributeError(
"%s object has no attribute %s" % (self, name)
)
a = A(21)
a._foo = lambda self: "answer is %s" % (self.x * 2)
print a.foo()
More information about the Python-list
mailing list