是否可以在 python 中进行中缀函数组合而不将函数包装在某些装饰器中?

问题描述 投票:0回答:1

标题说明了一切。看到很多答案,人们已经实现了

f @ g
,但这需要将
f
g
包装在一些
infix
装饰器或类中。有可能让它发挥作用吗?也许通过修补某个类,所有函数都是其实例或其他什么?

python functional-programming dsl infix-notation
1个回答
0
投票

我不确定我是否正确回答了你的问题,但正如你在问题中所说,你可以修补课程并添加

__matmul__
魔术方法。例如:

class A:
    def __init__(self):
        self.v = 10

# patch the A class to work with the `@` operator:
A.__matmul__ = lambda self, other: self.v * other.v

print(A() @ A())

打印:

100
© www.soinside.com 2019 - 2024. All rights reserved.