class Father:#2.7版本的老式類
def __init__(self):
pass
def function(self):
print(type(self))
print(isinstance(self, Son))
print(isinstance(self, Father))
print(self.mlist)
class Son(Father):
def __init__(self):
self.mlist = [1, 2, 3]
def function(self):
Father.function(self)
s = Son()
s.function()
輸出:
<type 'instance'>
True
True
[1, 2, 3]
這個例子程序中,有一點顛覆了我最近學習python後建立在大腦中的知識大廈。原來以爲python中類的方法中的self關鍵字只是一個書寫習慣,在調用類的方法的時候根本無需關心。然後在這個例子中卻發現self的值使Father的function方法中的內容正常執行了。非常奇妙。
由此,這個特性也用來解決了用戶重載新式類中__getattribute__方法時無限遞歸__getattribute__方法自己的bug