Overriding methods per-object
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Fri Apr 17 22:41:49 EDT 2009
On Fri, 17 Apr 2009 18:22:49 -0700, Pavel Panchekha wrote:
> I've got an object which has a method, __nonzero__ The problem is, that
> method is attached to that object not that class
>
>> a = GeneralTypeOfObject()
>> a.__nonzero__ = lambda: False
>> a.__nonzero__()
> False
>
> But:
>
>> bool(a)
> True
>
> What to do?
(1) Don't do that.
(2) If you *really* have to do that, you can tell the class to look at
the instance:
class GeneralTypeOfObject(object):
def __nonzero__(self):
try:
return self.__dict__['__nonzero__']
except KeyError:
return something
(3) But a better solution might be to subclass the class and use an
instance of that instead. You can even change the class on the fly.
a.__class__ = SubclassGeneralTypeOfObject # note the lack of brackets
--
Steven
More information about the Python-list
mailing list