是。例如,有
__radd__。另外,没有用于
__le__(),
__ge__()等的对象,但是正如乔尔·科内特(Joel
Cornett)正确地观察到的那样,如果仅定义
__lt__,则
a > b调用的
__lt__功能
b,这提供了一种解决方法。
>>> class My_Num(object):... def __init__(self, val):... self.val = val... def __radd__(self, other_num):... if isinstance(other_num, My_Num):... return self.val + other_num.val... else:... return self.val + other_num... >>> n1 = My_Num(1)>>> n2 = 3>>> >>> print n2 + n14>>> print n1 + n2Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: unsupported operand type(s) for +: 'My_Num' and 'int'
请注意,至少在某些情况下,这样做是合理的:
>>> class My_Num(object):... def __init__(self, val):... self.val = val... def __add__(self, other_num):... if isinstance(other_num, My_Num):... return self.val + other_num.val... else:... return self.val + other_num... __radd__ = __add__
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)