Python 从另一个函数中访问类函数中的变量?
我无法运行代码,因为MyApp初始化的帧的范围。下面是一个浓缩的示例应用程序,它演示了我的问题Python 从另一个函数中访问类函数中的变量?,python,python-2.7,wxpython,Python,Python 2.7,Wxpython,我无法运行代码,因为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")
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()
导入wx
类MyApp(wx.App):
def uu init(self):#如果没有一些代码,您的问题是“东西不工作。为什么不?”请详细询问您的编程问题。我们不需要任何背景信息。*更新-添加代码此代码为我运行。也许您应该发布您收到的错误消息,或者指定“应用程序未运行”self.nameField的含义。该字段尚未声明,并且与nameField不同。还有其他问题。python中是否没有办法在类定义中创建的函数中声明变量?在我上面的示例程序中,我可以不在那里创建nameField变量而将其作为全局变量吗?@travisook您可以这样做,尽管您的IDE/编译器可能会为“声明的实例变量在uuu init_u
之外”生成警告。我在答案的末尾添加了一个链接,提供了更多信息,您还可以了解全局变量,如果需要,还可以创建一个关于全局变量的单独问题。