- 论坛徽章:
- 0
|
看一个例子:
- >>> class A():
- ... def __init__(self, n):
- ... self.data = n
- ... def __add__(self, i):
- ... return self.data + i
- ...
- >>> a1 = A(1)
- >>> a2 = A(2)
- >>> a1 + 2
- 3
- >>> 2 + a2
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- TypeError: unsupported operand type(s) for +: 'int' and 'instance'
- >>> a1 + a2
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- File "<stdin>", line 5, in __add__
- TypeError: unsupported operand type(s) for +: 'int' and 'instance'
- >>> class A():
- ... def __init__(self, n):
- ... self.data = n
- ... def __add__(self, i):
- ... return self.data + i
- ... def __radd__(self, i):
- ... return self.data +i
- ...
- >>> a1 = A(1)
- >>> a2 = A(2)
- >>> a1 + a2
- 3
- >>>
复制代码
有以上可以看出:类中两元运算符是有方向性的
‘+’ 运算符:
__add__ method 是 左结合
__radd__ method 是 右结合
当左结合和右结合都定义时,才能实现类的两个对象运用 '+' 来计算
a1 + 2
此表达式计算时:a1 调用 '__add__' method
2 + a2
此表达式计算时:a2 调用 '__radd__' method
a1 + a2
此表达式计算时:a1 调用 '__add__' method,a2 调用 '__radd__' method
类似的运算符有:
- 与:& __and__, __rand__
- 或:| __or__, __ror__
- 异或:^ __xor__, __rxor__
- 加:+ __add__, __radd__
- 减:- __sub__, __rsub__
- 乘:* __mul__, __rmul__
- 除:/ __div__, __rdiv__
- 整除:// __floordiv__, __rfloordiv__
- 右移:>> __rshift__, __rrshift__
- 左移:<< __lshift__, __rlshift__
- ...
复制代码
[ 本帖最后由 爱知 于 2009-1-10 11:51 编辑 ] |
|