|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 汪蛋 于 2017-9-9 19:49 编辑
实例一:
- class A(int):
- def __add__(self, other):
- return int.__add__(self, other)
- def __sub__(self, other):
- return int.__sub__(self, other)
- a = A(3)
- b = A(5)
- print(a + b)
复制代码 类A是继承于int类,并且对__add__和__sub__函数进行了重写。调用了__add__函数后,self即加号左边的a,other即加号右边的b,运行结果为“8”。
实例二:
- class A(int):
- def __add__(self, other):
- return self + other
- def __sub__(self, other):
- return self + other
- a = A(3)
- b = A(5)
- print(a + b)
复制代码 上面所示的例子是不正确的,会陷入无限递归,因为self是对象a,other是对象b,那么__add__被调用之后,return a+b,也就是无限返回a+b,无解。程序更改如下:
- class A(int):
- def __add__(self, other):
- return int(self) + int(other)
- def __sub__(self, other):
- return int(self) + int(other)
- a = A(3)
- b = A(5)
- print(a + b)
复制代码 这样,self就是对象a的整型的值,other就是对象b的整型的值,就可以正常相加了。
魔法方法还有很多,如图所示:
|
|