Skip to main content

运算符重写

前文代码中:chain = chat_prompt_template | model 在语法上使用了|运算符的重写

在 Python 中,运算符(如 +、|)的行为由类的魔法方法决定。例如:

  • a + b 本质调用的是 a.add(b)
  • a | b 本质调用的是 a.or(b)

只需要自行实现类的__or__方法,即可对|符号的功能进行重写。

示例:

  • 让 a | b | c 的代码得到一个自定义的类对象(类似列表即[a, b, c])
  • 调用run方法依次输出a、b、c
  • 我们需要重写|即__or__方法
class Test(object):
def __init__(self, name):
self.name = name

def __str__(self): # 直接打印Test对象会打印内存地址
return self.name

def __or__(self, other): # other指或运算符右边的对象
return MySequence(self, other)


class MySequence(object):
def __init__(self, *args):
self.sequence = []
for arg in args:
self.sequence.append(arg)

def __or__(self, other):
self.sequence.append(other)
return self

def run(self):
for i in self.sequence:
print(i)


if __name__ == "__main__":
a = Test("a")
b = Test("b")
c = Test("c")

# a.__or__(b)
d = a | b | c # [a,b,c]
d.run()
print(type(d))