0

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?

1
  • Please learn not to use global. That's what parameters and return values are for. Commented Aug 29, 2014 at 5:24

1 Answer 1

2

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()
Sign up to request clarification or add additional context in comments.

5 Comments

I should probably pass it as an argument into the functions eh? What would be the tweaks to the example above to have it proper?
@DeucePie: I edited my answer to add an example. One way is to store the value as an attribute of the object.
Thanks, this has helped but I have run into another error down the line with the variable in another function but being used to form some JSON. If I make it {'filename': trigger} I get global name is not defined or if i make it {'filename': self.trigger} it says TypeError: <type 'type'> is not JSON serializable
@DeucePie: You should probably ask a separate question about that, as it sounds like an unrelated issue and that's not part of the code that you posted.
I will in 60 minutes... ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.