尽管您可能希望为该类选择一个更合适的名称,但是您可以将hack类几乎用作编写器的装饰器。
像这样:
class Composable(object): def __init__(self, function): self.function = function def __call__(self, *args, **kwargs): return self.function(*args, **kwargs) def __mul__(self, other): @Composable def composed(*args, **kwargs): return self.function(other(*args, **kwargs)) return composed def __rmul__(self, other): @Composable def composed(*args, **kwargs): return other(self.function(*args, **kwargs)) return composed
然后,您可以像这样装饰功能:
@Composabledef sub3(n): return n - 3@Composabledef square(n): return n * n
然后像这样组成它们:
(square * sub3)(n)
基本上,这是使用hack类完成的事情,只是将其用作装饰器。



