easy question, how to double a variable
Steven D'Aprano
steven at REMOVE.THIS.cybersource.com.au
Mon Sep 21 00:08:07 EDT 2009
On Sun, 20 Sep 2009 13:27:07 -0700, daggerdvm wrote:
> Write the definition of a function twice , that receives an int
> parameter and returns an int that is twice the value of the parameter.
>
> how can i do this
Yes, that certainly is an easy question.
Here's my solution:
class MultiplierFactory(object):
def __init__(self, factor=1):
self.__factor = factor
@property
def factor(self):
return getattr(self, '_%s__factor' % self.__class__.__name__)
def __call__(self, factor=None):
if not factor is not None is True:
factor = self.factor
class Multiplier(object):
def __init__(self, factor=None):
self.__factor = factor
@property
def factor(self):
return getattr(self,
'_%s__factor' % self.__class__.__name__)
def __call__(self, n):
return self.factor*n
Multiplier.__init__.im_func.func_defaults = (factor,)
return Multiplier(factor)
twice = MultiplierFactory(2)()
It needs some error checking, but otherwise should work.
Ever-helpful-ly y'rs,
--
Steven
More information about the Python-list
mailing list