本周在 comp.lang.python 上, Steven D'Aprano发布了一段“有趣”的代码,作为对家庭作业问题的开玩笑回答。这里是:
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)()
我们知道这twice
相当于答案:
def twice(x):
return 2*x
从名称中Multiplier
,MultiplierFactory
我们可以了解代码在做什么,但我们不确定确切的内部结构。让我们先简化它。
逻辑
if not factor is not None is True:
factor = self.factor
not factor is not None is True
等价于not factor is not None
, 这也是factor is None
. 结果:
if factor is None:
factor = self.factor
到目前为止,这很容易:)
属性访问
另一个有趣的地方是好奇的factor
访问器。
def factor(self):
return getattr(self, '_%s__factor' % self.__class__.__name__)
在初始化期间MultiplierFactory
,self.__factor
设置。但稍后,代码访问self.factor
.
然后似乎:
getattr(self, '_%s__factor' % self.__class__.__name__)
正在做的正是“ self.__factor
”。
我们可以总是以这种方式访问属性吗?
def mygetattr(self, attr):
return getattr(self, '_%s%s' % (self.__class__.__name__, attr))
动态改变函数签名
无论如何,在这一点上,这是简化的代码:
class MultiplierFactory(object):
def __init__(self, factor=1):
self.factor = factor
def __call__(self, factor=None):
if factor is None:
factor = self.factor
class Multiplier(object):
def __init__(self, factor=None):
self.factor = factor
def __call__(self, n):
return self.factor*n
Multiplier.__init__.im_func.func_defaults = (factor,)
return Multiplier(factor)
twice = MultiplierFactory(2)()
代码现在几乎是干净的。唯一令人费解的可能是:
Multiplier.__init__.im_func.func_defaults = (factor,)
里面有什么?我查看了数据模型文档,发现它func_defaults
是“一个元组,其中包含那些具有默认值的参数的默认参数值,或者如果没有参数具有默认值,则为 None ”。我们只是 factor
在这里更改参数的默认值 __init__
吗?生成的代码将是:
class MultiplierFactory(object):
def __init__(self, factor=1):
self.factor = factor
def __call__(self, factor=None):
if factor is None:
factor = self.factor
class Multiplier(object):
def __init__(self, innerfactor=factor):
self.factor = innerfactor
def __call__(self, n):
return self.factor*n
return Multiplier(factor)
twice = MultiplierFactory(2)()
这意味着动态设置默认值只是无用的噪音,因为Multiplier
在没有默认参数的情况下永远不会被调用,对吧?
我们可能可以将其简化为:
class MultiplierFactory(object):
def __init__(self, factor=1):
self.factor = factor
def __call__(self, factor=None):
if factor is None:
factor = self.factor
def my_multiplier(n):
return factor*n
return my_multiplier
twice = MultiplierFactory(2)() # similar to MultiplierFactory()(2)
正确的?
对于那些急于“这不是一个真正的问题”的人......再读一遍,我的问题是粗体+斜体