Overriding methods per-object

Chris Rebert clp2 at rebertia.com
Sat Apr 18 03:35:36 CEST 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

> 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

I have a blog:

More information about the Python-list mailing list