为什么我无法从 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()
I'm trying to remove a method from an class instance derived from a Tkinter window using the delattr
built in function. However, I get the following error. What am I doing wrong?
Error :
AttributeError: Class instance has no attribute 'wm_title'
An example :
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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不能以这种方式删除类方法,因为类方法是类的属性,而不是对象的属性。
当您通过
object.method()
调用方法时,Python实际上是在调用Class.method(object)
。 (这也是为什么您必须在类方法中声明self
参数,但在调用该方法时实际上并不为self
传递任何值。)如果您愿意,您可以可以调用
del Class.wm_title
。 (不过,我不确定你为什么想要这样做。)You can't delete a class method that way because class methods are properties of classes, not objects.
When you invoke a method via
object.method()
, python is actually callingClass.method(object)
. (This is also why you must declare aself
argument in class methods, yet you do not actually pass any value forself
when invoking that method.)If you want, you could call
del Class.wm_title
. (I'm not sure why you want to, though.)