【问题标题】:Access a variable in a Class function from in another function? [closed]从另一个函数中访问类函数中的变量? [关闭]
【发布时间】:2016-04-11 09:53:12
【问题描述】:

由于 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 超出了尝试使用它的函数的范围?

【问题讨论】:

  • 没有一些代码,你的问题是“东西不起作用。为什么不呢?”
  • 请详细询问您的编程问题。我们不需要任何这些背景信息。
  • *更新 - 添加代码
  • 此代码为我运行。也许您应该发布您收到的错误消息,或者以其他方式指定“应用程序未运行”的含义
  • self.nameField 没有被声明,与 nameField 不同。还有其他问题。

标签: python python-2.7 wxpython


【解决方案1】:

您的实例变量声明被声明为您的函数无法访问的局部变量。您将改为在 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()

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

【讨论】:

  • python 中没有办法在类定义中创建的函数中声明变量吗?在我上面的示例程序中,我可以不在那里创建 nameField 变量而是作为全局变量吗?
  • @TravisCook 你可以做这样的事情,尽管你的 IDE/编译器可能会为“declared instance variable outside of __init__”生成一个警告。我在答案末尾添加了一个链接,其中包含更多信息,您还可以了解全局变量并根据需要创建一个单独的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-28
  • 2014-10-28
  • 1970-01-01
  • 2022-10-24
  • 2022-12-06
  • 1970-01-01
相关资源
最近更新 更多