基本上我的问题:如果我有一个给定的 Container 类,是否有一种优雅的方式
class Container:
def __init__(self, value):
self.value = value
将任何运算符传递给容器类的值参数?
因此,一个明显的解决方案是自行覆盖任何单个运算符。例如对于
+
我可以:class Container:
def __init__(self, value):
self.value = value
def __add__(self, other):
return self.value + other
所以例如
c1 = Container(1)
c1 += 1
print(c1)
会导致
2
和
c2 = Container("ab")
c2 += "c"
print(c2)
会导致
abc
所以我能做的是覆盖所有来自 python 的算术内置函数。但我的问题是,对于任何运营商,是否有更优雅(更短)的方法来做到这一点?
最佳答案
您可以排除一些更重复的样板:
import operator
class Container:
def __init__(self, value):
self.value = value
def _generic_op(f):
def _(self, other):
return f(self.value, other)
return _
__add__ = _generic_op(operator.add)
__sub__ = _generic_op(operator.sub)
__mul__ = _generic_op(operator.mul)
# etc
# No need for _generic_op as a class attribute
del _generic_op
关于python - 在python中将运算符传递给属性的优雅方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61785254/