Overriding member methods in __init__

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Mon Dec 3 09:04:43 EST 2007


c james a écrit :
> Given a condition at the time a class is instantiated, I want to change
> how __call__ is used.  From the example below, self.no is using self.yes
> but self.__call__ is not.  Can someone please explain why?

IIRC, you can't override __magic__ methods on a per-instance basis.

> EXAMPLE:
> class YesNo(object):
>     def __init__(self, which):
>         self.no = self.yes
>         self.__call__ = self.yes
> 
>     def yes(self, val):
>         print 'Yes', val
> 
>     def no(self, val):
>         print 'No', val
> 
>     def __call__(self, val):
>         raise NotImplementedError()


This should do the trick:

class YesNo(object):
   def __init__(self, which):
     self.which = which

   def __call__(self, val):
     return (self.no, self.yes)[self.which](val)

   def yes(self, val):
     print 'Yes', val

   def no(self, val):
     print 'No', val



More information about the Python-list mailing list