One Python 2.1 idea
Moshe Zadka
moshez at zadka.site.co.il
Fri Dec 29 01:59:47 EST 2000
On Thu, 28 Dec 2000, "Alex Martelli" <aleaxit at yahoo.com> wrote:
> Now, I find out that, for that one instance only, I want to
> override the normal Ogre.foo method with another function
> which I also happen to have around:
>
> def fun(self):
> print 'have fun!'
>
>
> What are the 'good Pythonic ways' to do this, as opposed to
> 'dirty tricks'? It seemed to me that, say:
>
> x.foo = new.instancemethod(fun, x, Ogre)
>
> might be simpler and clearer than some alternative such as:
>
> x.__class__ = new.classobj('NewOgre', (Ogre,), {'foo':fun})
Personally, I avoid the ``new'' module completely (last I checked,
it wasn't portable to Jython, and it's all around tricky).
I'd simply do:
class _temp(Ogre):
foo = fun
x.__class__ = _temp
Sometimes even encapsulating it in a function:
def add_method_to_instance(instance, name, function):
class _temp(instance.__class__):
pass
setattr(_temp, name, function)
instance.__class__ = _temp
One additional benefit of the __class__ method is that it is
honest: you change the class when you changed the methods,
because behaviour *has* changed.
--
Moshe Zadka <sig at zadka.site.co.il>
This is a signature anti-virus.
Please stop the spread of signature viruses!
More information about the Python-list
mailing list