2011-09-09 54 views
2

我試圖使用內置的功能delattr從Tkinter的窗口派生的類實例中刪除的方法。但是,我收到以下錯誤。我究竟做錯了什麼?爲什麼我不能刪除一個Tkinter的窗口的方法/屬性?

錯誤:

AttributeError: Class instance has no attribute 'wm_title' 

一個例子:

import Tkinter as tk 

class Class (tk.Tk) : 
    def __init__ (self) : 
     tk.Tk.__init__(self) 

     # The method is clearly there, seeing as this works. 
     self.wm_title('') 

     # This raises an AttributeError. 
     delattr(self, 'wm_title') 


c = Class() 
c.mainloop() 

回答

2

不能刪除一個類的方法,那是因爲類方法是類,而不是對象的屬性。

當您通過object.method()調用一個方法,Python是實際調用Class.method(object)。 (這也是爲什麼你必須聲明類方法self參數,但你調用該方法時,實際上不傳遞任何值self

如果你願意,你可以調用del Class.wm_title。 (我不知道爲什麼你想,雖然)。

相關問題