python - 在python中将运算符传递给属性的优雅方式

标签 python

基本上我的问题:如果我有一个给定的 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/

相关文章:

php - 如何使用PHP调用python脚本实时返回结果?

python - 我正在寻找一个 Python 多人游戏服务器项目

python - 使用来自其他 Series/DataFrame 的值(曲线下面积)过滤 DataFrame 中的每个 X

python - 在 Keras 下缩小 Densenet121

python - 无法使用 Tkinter 打印出 "event.char"

Java 通过引用转码到 Python

python - 如何将以下 tf 1.x 代码转换为 tf 2.0(对现有代码进行最少的更改)

python - 如何在考虑边界的情况下获取 numpy 数组中的相邻元素?

python - 有没有办法在 Python 2.7.5 的 MySQLdb.connect 中将 secure_auth 设置为 false?

python - 需要将随机输出转换为字符串