One Python 2.1 idea
Alex Martelli
aleaxit at yahoo.com
Thu Dec 28 04:35:31 EST 2000
"Tim Peters" <tim.one at home.com> wrote in message
news:mailman.977978231.26163.python-list at python.org...
[snip]
> About x.foo = x.foo, I never saw anyone suggest that to save time, before
> this thread. Where it did come up several times over the years was people
> trying to customize how a method works for a particular instance, rather
> than make a proper subclass. Since Python made instance.__class__
writable,
> I don't see any excuse for *that* form of trickery anymore.
Might I ask for a clarification of this latter thought...?
Say I have a class Ogre with a few methods:
class Ogre(Bugaboo):
def fee(self):
print 'fee'
def fie(self):
print 'fie'
def foo(self):
print 'foo'
def fum(self):
print 'fum'
and several instances thereof, one of which is referenced by
variable x.
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})
Are you saying the second approach is preferable? Or is there
some even-simpler one that I'm missing? I do realize a cycle
of references is generated by the new.instancemethod, as
discussed on this thread -- is that the only issue, and does
GC solve it (if no __del__'s are present), or are there others?
Alex
More information about the Python-list
mailing list