關(guān)于實(shí)例p1,p2的指向
class Programer(object): ? ?def __init__(self,name,age): ? ? ? ?self.name = name ? ? ? ?if isinstance(age, int): ? ? ? ? ? ?self.age = age ? ? ? ?else: ? ? ? ? ? ?raise Exception('age must be int') ? ?def __eq__(self, other): ? ? ? ?if isinstance(other, Programer): ? ? ? ? ? ?if self.age == other.age: ? ? ? ? ? ? ? ?return Ture ? ? ? ? ? ?else: ? ? ? ? ? ? ? ?return False ? ? ? ?else: ? ? ? ? ? ?raise Exception('the type of object must be Programer') ? ?def __add__(self, other): ? ? ? ?if isinstance(other,Programer): ? ? ? ? ? ?return self.age + other.age ? ? ? ?else: ? ? ? ? ? ?raise Exception('the type og object must be Programer') if __name__ == '__main__': ? ?p1 = programer('abc', 54) ? ?p2 = programer('bbb', 25) ? ?print p1 == p2 ? ?print p1.age + p2.age?
?關(guān)鍵點(diǎn)不明白,p1,p2都是 Programer 的實(shí)例,當(dāng)調(diào)用 __eq__ 和 __add__ 方法的時(shí)候,self 是 指的實(shí)例, 為什么是 p1 而不是 p2 , ? p2 又是如何 被傳進(jìn)去變成 other 的 還望老師解答一二
2017-12-26
self也可以是p2啊,兩個(gè)實(shí)例運(yùn)算,它會(huì)在當(dāng)前類(lèi)中找出重寫(xiě)的方法進(jìn)行計(jì)算,沒(méi)有的話就會(huì)在父類(lèi)尋找