重新体会Python的魔术方法

2019-01-25  本文已影响0人  YouMyGod

以下会随着时间的推移,我会慢慢记录对python中魔术方法的理解

class Person:
    age = 5
    def __add__(self, other):
        return other - self.age

person = Person()
print(Person.__add__(person,3))
print(person.__add__(3))
打印结果
D:\Python\Python37\python.exe D:/mysite/polls/test.py
-2
-2

Process finished with exit code 0

可以看出如果是类本身去调用魔术方法的时候必须要传递自身的对象,而对象本身调用魔术方法直接传递参数即可,这点比较绕。

上一篇下一篇

猜你喜欢

热点阅读