Overriding methods per-object
Chris Rebert
clp2 at rebertia.com
Fri Apr 17 21:35:36 EDT 2009
On Fri, Apr 17, 2009 at 6:22 PM, Pavel Panchekha <PavPanchekha at gmail.com> 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
This is as documented. See
http://docs.python.org/3.0/reference/datamodel.html#special-lookup
>
> What to do?
Either wrap the object in another object of a class that does define
__bool__, or change GeneralTypeOfObject so it defines __bool__(),
possibly having its __bool__ delegate to another method, which you
could then override on a per-object basis similar to your current
code.
Cheers,
Chris
--
I have a blog:
http://blog.rebertia.com
More information about the Python-list
mailing list