Overriding member methods in __init__
Arnaud Delobelle
arnodel at googlemail.com
Mon Dec 3 12:53:01 EST 2007
On Dec 3, 3:36 pm, Hrvoje Niksic <hnik... at xemacs.org> wrote:
> Allowing instance lookup of __call__ would slow down normal uses of
> the internal __call__ mechanism. Since it used for all function and
> method calls, it needs to remain extremely fast. If you're really
> worried about performance, you can define YesNo.__new__ to return
> either a Yes instance or a No instance, depending on the value:
>
> class YesNo(object):
> def __new__(cls, which):
> if which:
> return object.__new__(Yes)
> else:
> return object.__new__(No)
>
> def yes(self, val):
> print 'Yes', val
>
> def no(self, val):
> print 'No', val
>
> class Yes(YesNo):
> def __call__(self, val):
> self.yes(val) # no check at every call
>
> class No(YesNo):
> def __call__(self, val):
> self.no(val) # likewise
>
Why not simply do:
class YesNo(object):
def __init__(self, which):
self.yesno = which and self.yes or self.no
def yes(self, val):
print 'Yes', val
def no(self, val):
print 'No', val
def __call__(self, val):
self.yesno(val)
I don't know which is fastest but I don't think there would be much
difference.
--
Arnaud
More information about the Python-list
mailing list