从另一个函数访问 Class 函数中的变量?

Access a variable in a Class function from in another function?

由于 MyApp 初始化的框架范围,我无法获取 运行 的代码。这是一个演示我的问题的压缩示例应用程序

import wx

class MyApp(wx.App):
    def OnInit(self):
        self.InitWindow()
        return True

    def InitWindow(self):
        frame = wx.Frame(None, wx.ID_ANY, "Travis's sample problem app")
        nameField = wx.TextCtrl(frame)

        clickbtn = wx.Button(frame, 0, label="click me")
        frame.Bind(wx.EVT_BUTTON, self.clickedAction, clickbtn)
        frame.Show()

    def clickedAction(self, e):
        #Here we will get an error: "object has no attribute 'nameField'"
        print self.nameField.GetString()
        #what am I doing wrong?

app = MyApp()
app.MainLoop()

为什么 nameField 超出了尝试使用它的函数的范围?

您的实例变量声明被声明为您的函数无法访问的局部变量。您可以在 init 中用 self. 声明它们,以使它们的范围包括整个实例。

改成这样:

import wx

class MyApp(wx.App):
   def __init__(self):  #<-- runs when we create MyApp
        #stuff here
        self.nameField = wx.TextCtrl(frame)  #<--scope is for all of MyApp
        #stuff

    def clickedAction(self, e):
        #stuff
app = MyApp()
app.MainLoop()

您可以详细了解 class 变量和实例变量 here 之间的区别。