python中自定义对象中的算数运算:
例如:算数加法(pycharm):
class result(int): # 利用int方法来实现对象间的算数运算
def __add__(self, other):
return int.__add__(self, other)
def __sub__(self, other):
return int.__sub__(self, other)
number1 = int(input("请输入需要添加的数字1:"))
number2 = int(input("请输入需要添加的数字2:"))
Result1 = result(number1)
Result2 = result(number2)
Result = Result1 + Result2
print(Result)
结果(IDLE):
>>> class result(int): # 利用int方法来实现对象间的算数运算
def __add__(self, other):
return int.__add__(self, other)
def __sub__(self, other):
return int.__sub__(self, other)
>>> number1 = int(input("请输入需要添加的数字1:"))
请输入需要添加的数字1:3
>>> number2 = int(input("请输入需要添加的数字2:"))
请输入需要添加的数字2:5
>>> Result1 = result(number1)
>>> Result2 = result(number2)
>>> Result = Result1 + Result2
>>> print(Result)
8
例图: