的Python - 实例属性__init __()
问题描述:
我得到了下面的代码有问题的警告之外定义:的Python - 实例属性__init __()
from tkinter import *
from tkinter import ttk
class Autocomplete(Frame, object):
def __init__(self, *args, **kwargs):
super(Autocomplete, self).__init__(*args, **kwargs)
self.list = []
def build(self, width, height, entries):
# I get the warning for the following 8 lines:
self._entries = entries
self.listbox_height = height
self.entry_width = width
self.text = StringVar()
self.entry = ttk.Entry(self, textvariable=self.text, width=self.entry_width)
self.frame = Frame(self)
self.listbox = Listbox(self.frame, height=self.listbox_height, width=self.entry_width)
self.dropdown = Listbox(self.frame, height=self.listbox_height, width=self.entry_width, background="#cfeff9",
takefocus=0)
self.entry.pack()
self.frame.pack()
self.listbox.grid(column=0, row=0, sticky=N)
self.dropdown.grid(column=0, row=0, sticky=N)
self.dropdown.grid_forget()
return self
root = Frame(Tk())
autocomplete = Autocomplete(root).build(74, 10, entries)
root.pack()
autocomplete.pack()
mainloop()
我应该如何解决这个问题?我尝试将所有内容都移动到init,但是在创建Autocompelete对象的行中传递参数时出现了一些错误。所以请给我提供我必须做的所有改变。不只是像你必须移动它们一样。 我可以通过添加8条将所有变量赋值为None的定义行来修复警告,但我认为这是一个很愚蠢的解决方案。那么,正确的做法是什么?
答
它总是重要的是要记住,并不是所有的警告都要求固定。警告只是警告。他们应该指出代码的特定部分,因为这是一个“常见”问题的来源。但有时你需要/想要这样做。
我可以通过添加8条限定线分配无所有变量的
这只是“沉默”的警告,在我看来,这只是作为无视警告良好修复警告。
那么什么是正确的事情?
正确的方法是只使用__init__
。我做了一个快速测试,我没有任何问题。
然而,这只是一个例子一个如何能做到这一点。我没有检查什么Frame
想为__init__
论据,它可能会导致冲突:
from tkinter import *
from tkinter import ttk
class Autocomplete(Frame, object):
def __init__(self, *args, **kwargs):
width, height, entries = kwargs.pop('width'), kwargs.pop('height'), kwargs.pop('entries')
super(Autocomplete, self).__init__(*args, **kwargs)
self.list = []
self._entries = entries
self.listbox_height = height
self.entry_width = width
self.text = StringVar()
self.entry = ttk.Entry(self, textvariable=self.text, width=self.entry_width)
self.frame = Frame(self)
self.listbox = Listbox(self.frame, height=self.listbox_height, width=self.entry_width)
self.dropdown = Listbox(self.frame, height=self.listbox_height, width=self.entry_width, background="#cfeff9",
takefocus=0)
self.entry.pack()
self.frame.pack()
self.listbox.grid(column=0, row=0, sticky=N)
self.dropdown.grid(column=0, row=0, sticky=N)
self.dropdown.grid_forget()
root = Frame(Tk())
autocomplete = Autocomplete(root, width=74, height=10, entries=entries)
root.pack()
autocomplete.pack()
mainloop()
+0
感谢我的问题是与不添加宽度,高度,项= kwargs.pop( '宽'),kwargs.pop( '高度'),kwargs.pop( '项目')!我不知道什么是kwargs,并且我得到了这个错误。谢谢。 –
*“我可以修复警告通过添加8个定义行没有分配到所有的变量” * ...这是警告告诉你要做什么。通常情况下,在'__init__'方法中未定义的对象上突然出现属性会使调试更加困难。 – CoryKramer
也是,这非常依赖你使用的棉绒。 – turbulencetoo
@turbulencetoo我用pycharm –