有人能用简单的语言向我解释魔术方法和操作符重载吗?

2024-04-20 11:14:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我无法理解__add__ / __sub__方法,它们为什么需要它们,它们是如何工作的,以及重载的概念,谢谢


Tags: 方法add概念
1条回答
网友
1楼 · 发布于 2024-04-20 11:14:55

它使您的生活更轻松,使您的代码更易于阅读。请看一看我的简单用例,我让你理解。你知道吗

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

相关问题 更多 >