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.
I only have one file: app.py 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: `
NameError: global name 'globvar' is not defined.
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?
EDIT bottom of file with no indentation:
app = MyApp(False)
logFile = open('C:/Python26/temp/test.txt', 'w')
globvar = 7
ser = serial.Serial('com5',115200,timeout=0.01)
app.MainLoop()
Then in my first class I have:
class MyApp(wx.App):
def MainLoop(self):
line = ser.readline()
if len(line) > 2:
global globvar
globvar = line
And in my second class I have:
class MyFrame(wx.Frame):
def OnMove(self, event):
pos = event.GetPosition()
global globvar
self.posCtrl.SetValue("%s, %s" % (globvar, pos.y))
These are all in the same file. The error text is:
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
All parameters are passed by reference (in the C++ sense). The Python language doesn’t have pass by value (in the C++ sense) although it can be simulated by copying, and certain things are automatically copied on mutate like numbers, strings, and tuples such that they may give the appearance of having been passed by value. To be very specific python is call-by-object (aka call-by-sharing, call-by-object-reference) as pointed out here on stackoverflow previously.
To make a variable global you need to make the first assignment to it outside of any function or create in a function with the global keyword. To modify it in a function you’ll also need to use the global keyword. See here for more details on the global keyword.
For example:
yields output of: