07 #### `__add__`用于对象相加或者数据+-*/* `*`都可以

# __add__
class Info:

    def __init__(self, number):
        self.number = number

    def __add__(self, other):
        # return self.number + other.number  # self.number  表示obj1中传入的数据:10,other.number 表示obj2.中传入的数据:10
        return Info(self.number + other.number)  # 也可返回一个对象,


"""obj1 = Info(10)
obj2 = Info(10)
print(obj1 + obj2)  # TypeError: unsupported operand type(s) for +: 'Info' and 'Info' 不支持,如果要支持,"""
# 在类方法中,增加__add__方法
obj1 = Info(10)
obj2 = Info(10)
print(obj1 + obj2)  # 等于:obj1.__add__(obj2)

posted @ 2024-09-28 07:31  jhchena  阅读(1)  评论(0编辑  收藏  举报