2024-04-20 11:14:55 发布
网友
我无法理解__add__ / __sub__方法,它们为什么需要它们,它们是如何工作的,以及重载的概念,谢谢
__add__ / __sub__
它使您的生活更轻松,使您的代码更易于阅读。请看一看我的简单用例,我让你理解。你知道吗
class Car: def __init__(self): self.__total = 0 def buy(self, count): self.__total += count def __add__(self, other): return self.total + other.total @property def total(self): return self.__total toyota = Car() honda = Car() toyota.buy(3) print(toyota.total) # prints 3 honda.buy(5) print(honda.total) # prints 5 car_total = honda + toyota print(car_total) # prints 8
它使您的生活更轻松,使您的代码更易于阅读。请看一看我的简单用例,我让你理解。你知道吗
相关问题 更多 >
编程相关推荐