1
class Example(tk.Frame):
    def __init__(self, parent):
        global p
        p = 1.1
        ....

    def looper(self):
        if self.keys['Prior']:
            p = p -.01
            self.draw()

This code comes back with UnboundLocalError: local variable 'p' referenced before assignment

I tried putting global p/p=1.1 down in the main routine outside of the Class and I got the same exact error. Somewhere I must be misunderstanding things. I thought global meant through the whole program...which is the way I want it...set it once and let it go throughout the program. What am I doing wrong?

hurturk
  • 5,214
  • 24
  • 41
confused
  • 1,283
  • 6
  • 21
  • 37
  • 1
    `global` goes in every function that needs to assign to the global (though why is it a global instead of an instance attribute, anyway?) – user2357112 Mar 28 '17 at 22:49
  • 1
    Also, be careful about using floats for looping. It is very easy to get results you don't want or expect. In all likelihood, you should be using integers or instances of `decimal.Decimal` instead. – John Y Mar 28 '17 at 23:04
  • Related, or possibly even a better duplicate (in the sense of asking the question that was on OP's mind, rather than the question that leads to the quickest fix for OP's code): http://stackoverflow.com/questions/25678032/how-does-pythons-global-keyword-work (note especially the higher explanatory quality of the answers found there). – John Y Mar 31 '17 at 14:49

1 Answers1

3

You can define p before class definition (not advised), if you are pointing it from a method:

p = None

class Example(tk.Frame):
    def __init__(self, parent):
        global p
        p = 1.1

    def looper(self):
        global p
        if ...

# modifying the global
p = 5

However, beware that every instance will modify it which doesn't make sense until you are having a singleton pattern or other purpose. Instead you should have p as instance variable:

class Example(tk.Frame):
    def __init__(self, parent):
        self.p = 1.1

    def looper(self):
        if self.keys['Prior']:
            self.p = self.p -.01
            self.draw()

# modifying the instance
my_instance = Example(..)
my_instance.p = 5
hurturk
  • 5,214
  • 24
  • 41