I am learning Python as I go and I am not getting what I am doing wrong with my variables and being to access them in functions.
I have recreated the general layout of my script in PythonFiddle and I got the same error
global trigger
class test(object):
def init(self):
trigger = 'hi'
self.step2()
def step2(self):
print '%s' % trigger
if __name__ == "__main__":
tester = test()
tester.init()`
Anyone have any ideas?
You need to mark the variable as global in every function where you assign to it. Put global trigger
inside your init
method.
Note that doing things this way is probably not a great idea. There's not much point to defining a class if it's just going to store its data in a global variable. One alternative would be:
class test(object):
def init(self):
self.trigger = 'hi'
self.step2()
def step2(self):
print '%s' % self.trigger
if __name__ == "__main__":
tester = test()
tester.init()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.