算术运算符__add__ 魔术方法,实现了数字类型之间的加法操作

class Test(object):
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def __add__(self, other):
        print('测试一下int 对象的相加')
        print('对象之间使用了+号')
        print("看下self.age这个属性是什么:", self.age)  # 18
        print("看下other.age这个属性是什么:", other.__dict__)  # {'name': '老王', 'age': 48}, 所以 other.age=48
        # print("看下这个属性是什么:", vars(other))  # {'name': '老王', 'age': 48}
        return self.age+other.age  # 18 + 48

xiaoming = Test('小明',18)
laowang = Test('老王',48)
res = xiaoming + laowang
print(res) # 66

其他算术运算符对应的魔术方法:
add(self, other) 定义加法的行为:+
sub(self, other) 定义减法的行为:-
mul(self, other) 定义乘法的行为:*
truediv(self, other) 定义真除法的行为:/
floordiv(self, other) 定义整数除法的行为://
mod(self, other) 定义取余算法的行为:%

更多的魔术方法参考地址转载自该处:https://www.cnblogs.com/nmb-musen/p/10861536.html

posted @ 2025-09-04 16:34  大海一个人听  阅读(8)  评论(0)    收藏  举报