gpt4 book ai didi

python - 为内置和类实例定义运算符

转载 作者:太空宇宙 更新时间:2023-11-03 12:41:08 27 4
gpt4 key购买 nike

在 Python 中,您可以通过定义 __add__ 来覆盖您的类的操作(例如,加法)。这将使添加具有其他值/实例的类实例成为可能,但您不能将内置函数添加到实例中:

foo = Foo()
bar = foo + 6 # Works
bar = 6 + foo # TypeError: unsupported operand type(s) for +: 'int' and 'Foo'

有什么方法可以启用它吗?

最佳答案

你必须定义方法 __radd__(self, other)当您的实例位于右侧时覆盖运算符 +

关于python - 为内置和类实例定义运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12990940/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com