一、知识梳理:
二、货币场景搭建:
1)代码展示:
class RMB:
count = 0
def __init__(self,yuan=0,jiao=0,fen=0):
self.__yuan = yuan
self.__jiao = jiao
self.__fen = fen
RMB.count += 1
def __add__(self, other):
temp = RMB()
temp.__yuan = self.__yuan + other.__yuan
temp.__jiao = self.__jiao + other.__jiao
temp.__fen = self.__fen + other.__fen
return temp
def __sub__(self, other):
temp = RMB()
temp.__yuan = self.__yuan - other.__yuan
temp.__jiao = self.__jiao - other.__jiao
temp.__fen = self.__fen - other.__fen
return temp
def __gt__(self, other):
if self.__yuan > other.__yuan:
return True
elif (self.__yuan == other.__yuan) and self.__jiao > other.__jiao:
return True
elif ((self.__yuan == other.__yuan) and (self.__jiao == other.__jiao)) and self.__fen > other.__fen:
return True
else:
return False
def __isub__(self, other=0):
self.__yuan -= 1
self.__jiao -= 1
self.__fen -= 1
def __iadd__(self, other=0):
self.__yuan += 1
self.__jiao += 1
self.__fen += 1
def __del__(self):
RMB.count -= 1
def __str__(self):
return f"{self.__yuan}元{self.__jiao}角{self.__fen}分,count={RMB.count}"
if __name__ == '__main__':
x = RMB(5,5,5)
print(f"x={x}")
y = RMB(3,3,3)
print(f"y={y}")
z = x + y
print(f"x+y={z}")
w = x - y
print(f"x-y={w}")
print(f"x > y的结果是{x > y}")
x.__isub__()
print(f"x自减之后,x={x}")
y.__iadd__()
print(f"y自增之后,y={y}")
2)结果展示:
x=5元5角5分,count=1
y=3元3角3分,count=2
x+y=8元8角8分,count=3
x-y=2元2角2分,count=3
x > y的结果是True
x自减之后,x=4元4角4分,count=3
y自增之后,y=4元4角4分,count=3