daisanosng 发表于 2020-5-23 20:17:36

算数运算求助

本帖最后由 daisanosng 于 2020-5-23 20:37 编辑

class New_int(int):
    def __radd__(self,other):
      returnint.__sub__(other,self)

a=New_int(1)
print(dir(a))
b=int(2)
print(dir(b))
print(b+a)

运行结果:
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dict__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__module__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
1

疑问:通过dir()函数查找,b对象有__add__()方法,为什么不调用b对象的__add__()方法,而调用a对象的
__radd__()方法?

xiaosi4081 发表于 2020-5-23 20:34:50

领鱼币

KevinHu 发表于 2020-5-23 20:37:51

xiaosi4081 发表于 2020-5-23 20:34
领鱼币

我艹

xiaosi4081 发表于 2020-5-23 20:38:50

KevinHu 发表于 2020-5-23 20:37
我艹

10鱼币到手{:10_256:}

永恒的蓝色梦想 发表于 2020-5-23 20:51:38

KevinHu 发表于 2020-5-23 20:37
我艹

我也艹

qiuyouzhi 发表于 2020-5-23 21:05:54

永恒的蓝色梦想 发表于 2020-5-23 20:51
我也艹

{:10_250:}
页: [1]
查看完整版本: 算数运算求助