python的微型运算符
MiniOperators的Python项目详细描述
这个库使得在python中添加扩展运算符变得非常简单 语言,或者将现有函数转换为二进制运算符。为了 例如,可以使用函数compose:
def compose(f, g): return lambda *args, **kwargs: f(g(*args, **kwargs))
把它变成一个运算符,|compose|:
compose = MiniOperator(compose)
然后,该运算符可以用作二进制运算符[1]:
f = math.sqrt |compose| (lambda x: x**2 + 1) f(0) # 1.0
如果始终使用这个|<name>|符号和括号 参数,不应该出现问题[2]。
此外,这样创建的运算符将支持通过 标准python约定__<name>__和__r<name>__特殊 方法。
文档
可以通过三种方式调用MiniOperator构造函数。 MiniOperator(f)创建名为f的运算符,该运算符使用f作为 默认操作[3]。也可以明确地传递名称: MiniOperator(name, f),其中name是字符串,将创建运算符 命名为name,使用f作为默认操作。最后,你可以创造 不指定默认方法的运算符:MiniOperator(name),其中 name是字符串,将导致运算符抛出 NotImplementedError用于大多数参数时。然而,一个班级 能够明确地重写__<name>__或__r<name>__来支持这个 接线员。
脚注
[1] | Of course, the initial function must be binary — that is, it must take two arguments — and other obvious restrications apply as well. |
[2] | The author would like to suggest using two spaces around the operator and to take special care parenthesizing expressions. |
[3] | That is, the name is derived from the ^{tt19}$ of the passed function. The author suggests not overrelying on this form. |