首页 > 解决方案 > 一个函数可以在同一个类中使用另一个函数吗?

问题描述

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

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

我还尝试将它们设为全局变量,但我收到 {SyntaxError: name 'note_input' is assigned to before global declaration}

否则,我尝试在函数之外但在类内创建变量,但我认为存在继承问题,因为无法识别“自我”。

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):...

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

标签: pythonfunctioninheritancetkinterglobal

解决方案


[..] 函数可以访问其他函数中的变量吗?

不可以。变量只能从其范围内访问。在您的情况下content_collector,您的变量属于该函数的本地范围,并且只能从该函数内访问。除了它们的作用域之外,变量还有一个生命周期;它们仅在函数执行时存在。虽然file_saveas执行content_collector不执行,因此此时变量不存在。

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

除了将变量设置为全局变量之外,您还可以将它们设置为实例变量,例如在__init__方法中,或者让content_collector它们返回这些值,例如:

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()

推荐阅读