python:如何将实例的方法调用转发到它的属性

标签 python python-2.7

class Number(object):
    def __init__(self):
        super(Number, self).__init__()
        self.data = 10

    def __getattr__(self, name):
        def _missing(*args, **kwargs):
            method = getattr(self.data, name)
            return method(args[0])

        return _missing

a = Number()
b = Number()

print a.__add__(10)   # this is ok!
print a + 10          # TypeError: "unsupported operand type(s) for +: 'Number' and 'int'"
print a + b           # TypeError: "unsupported operand type(s) for +: 'Number' and 'Number'"

问题: "a.__add__(10)"和 "a + 10"之间有什么区别,如何 Hook 运算符 "+"?

最佳答案

Python 只会使用实际的 __add__ 方法,而不是因为 __getattr__ 而“存在”的方法。

添加 __add__ = (10).__add__ 时效果很好。

所以您要做的是添加代理方法:

def __add__(self, *args): return self.data.__add__(*args)
def __sub__(self, *args): return self.data.__sub__(*args)
# ...

关于python:如何将实例的方法调用转发到它的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11629287/

相关文章:

python - 如何通过 key 访问列表?

python - 从不同长度的子子列表中查找全局最小值

python - 类型错误 : unbound method must be called with instance as first argument (got int instance instead) in Python 2

python - 如何通过 Python/C API 将 Python 实例传递给 C++

python - 优化程序的可变变量

python - 对常量进行分类(并能够确定其类别)

javascript - 通知不可点击一次 "read": error "notification_id is not defined"

python - ValueError : Found array with 0 sample (s) (shape= (0, 1) 而 MinMaxScaler 要求最小值为 1

python - 添加 SlugField 字段类型时出现问题 (Django 1.6.3)

python - file.seek() 和 read() 相对于当前位置