一个函数可以在同一个 Class 中使用另一个函数吗?

Can a Function use another Function within the same Class?

我想减少我的代码并想创建一个函数从另一个 Class 收集内容,然后将我未来的函数引用到 "content_collector" 以便能够访问变量(note_input, title_lable, ...)。

首先,如问题所述,Functions可以访问其他Functions中的变量吗?

我也试图让它们成为一个全局变量,但我收到一个{SyntaxError: name 'note_input' is assigned to before global declaration}

否则,我尝试在函数外但在 class 内创建变量,但我认为存在继承问题,因为无法识别 'self'。

class Functions:

    def content_collector(self):

        note_input = self.note_entry.get("1.0", "end-1c")
        title_label = self.title_entry.get()
        author_label = self.author_entry.get()
        year_label = self.year_entry.get()
        others_label = self.others_entry.get()

        global note_input, title_label, author_label, year_label, others_label


    def file_saveas(self):

       dic = {"title": title_label,
              "author": author_label,
              "year": year_label,
              "other": others_label,
              "note": note_input}

class EntryWidgets(Functions):

    def __init__(self, master):...

一如既往,非常感谢您提供有用的答案!

[..] can Functions access variables in other Functions?

没有。变量只能从其范围内访问。对于 content_collector,您的变量属于该函数的局部范围,只能从该函数内部访问。除了作用域之外,变量还有生命周期;它们仅在函数执行时存在。虽然file_saveas执行content_collector不执行,因此此时变量不存在。

至于你的 SyntaxError:正如它所说,你试图让你的变量成为全局变量给它们赋值之后。您需要将 global 语句移动到 content_collector 方法的开头。即使那样,这些名称也只有在 content_collector 至少执行一次后才能知道(因为只有到那时,这些名称才能通过 global 语句在局部函数范围之外使用)。在调用 content_collector 之前调用 file_saveas 会导致 NameError。

您可以将它们设为实例变量,而不是将它们设为全局变量,例如在 __init__ 方法中或让 content_collector return 这些值,例如:

class Functions:

    def content_collector(self):

        dic = {"note": self.note_entry.get("1.0", "end-1c"),
               "title": self.title_entry.get(),
               "author": self.author_entry.get(),
               "year": self.year_entry.get(),
               "other": self.others_entry.get()}
        return dic


    def file_saveas(self):

       dic = self.content_collector()