Overriding methods per-object

Pavel Panchekha PavPanchekha at gmail.com
Sun Apr 19 20:33:30 CEST 2009


On Apr 18, 9:43 pm, Aaron Brady <castiro... at gmail.com> wrote:
> 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.

I got it working. Thanks!



More information about the Python-list mailing list