Python - 在__init __()之外定义的实例属性

时间:2017-09-26 19:36:21

标签: python architecture initialization definition

我收到有关以下代码的警告:

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,但我认为这是一个非常愚蠢的解决方案。那么正确的做法是什么?

1 个答案:

答案 0 :(得分:3)

记住,并非所有警告都需要修复,这一点非常重要。警告只是警告。他们应该指出代码的特定部分,因为它是问题的“常见”来源。但有时你需要/想要这样做。

  

我可以通过添加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()
相关问题