Note that there are some explanatory texts on larger screens.

plurals
  1. POPython namespace and global variables
    text
    copied!<p>I've read several answers about making variables global and sharing them between classes with the class.var functionality, but none of those seem to work in my example.</p> <p>I only have one file: <code>app.py</code> which instantiates multiple classes. However, the variable that I want to make global isn't in a class, it's just in the main script. Then when I type global globvar in a function that is inside one of the classes, I get the error: `</p> <pre><code>NameError: global name 'globvar' is not defined. </code></pre> <p>How can I either pass this variable to the class by reference (I know, not pythonic language) so that the class can modify it but other classes can access it, or make it global so all the classes can access it?</p> <p><strong>EDIT</strong> bottom of file with no indentation: </p> <pre><code>app = MyApp(False) logFile = open('C:/Python26/temp/test.txt', 'w') globvar = 7 ser = serial.Serial('com5',115200,timeout=0.01) app.MainLoop() </code></pre> <p>Then in my first class I have:</p> <pre><code>class MyApp(wx.App): def MainLoop(self): line = ser.readline() if len(line) &gt; 2: global globvar globvar = line </code></pre> <p>And in my second class I have:</p> <pre><code>class MyFrame(wx.Frame): def OnMove(self, event): pos = event.GetPosition() global globvar self.posCtrl.SetValue("%s, %s" % (globvar, pos.y)) </code></pre> <p>These are all in the same file. The error text is: </p> <pre><code>Traceback (most recent call last): File "C:\Program Files (x86)\wxPython2.8 Docs and Demos\samples\mainloop\mainloop.py", line 66, in OnMove self.posCtrl.SetValue("%s, %s" % (globvar, pos.y)) NameError: global name 'globvar' is not defined </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload