小编chi*_*oon的帖子

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

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'"
Run Code Online (Sandbox Code Playgroud)

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

python python-2.7

5
推荐指数
1
解决办法
3699
查看次数

标签 统计

python ×1

python-2.7 ×1