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



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

您可以在这里阅读更多关于类变量和实例变量之间的区别。

最新更新