Overriding methods per-object

Aaron Brady castironpi at gmail.com
Sat Apr 18 21:43:24 EDT 2009


On Apr 17, 9:41 pm, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> 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
snip

I think you need to call the return, unlike you would in
'__getattr__'.
             return self.__dict__['__nonzero__']( )

You're free to use a different name for the method too.
             return self.custom_bool( )

And you don't even have to implement an ABC.  Er... /have/ to, that
is.



More information about the Python-list mailing list