Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
The importance of .self
-
I am a VERY new person to python and pythonista(not ot coding though, for I have been programming in Lua and C++ and Java for the last 8 months). So this error that i am getting is really bothering me here is the code and error. Please Help.
from scene import * class MyScene (Scene): def setup(self): # This will be called before the first frame is drawn. show = 0 pass def draw(self): # This will be called for every frame (typically 60 times per second). background(0, 0, 0) # Draw a red circle for every finger that touches the screen: fill(0.50, 1.00, 0.00) rect(100, 100, 150, 50) fill(1, 0, 0) if show == 1: #HERE IS WHERE MY ERROR IS TAKING PLACE ellipse(500, 400, 100, 100) for touch in self.touches.values(): #ellipse(touch.location.x - 50, touch.location.y - 50, 100, 100) if touch.location.x > 99: if touch.location.x < 251: if touch.location.y > 99: if touch.location.y < 151: show = 1 def touch_began(self, touch): pass def touch_moved(self, touch): pass def touch_ended(self, touch): pass run(MyScene())
The error says UnboundLocalError: local variable 'show' referenced before assignment
-
Change all instances of 'show' to 'self.show'. The show variable is a local variable only visible within a single function. The self.show variable is bound to the scene object and is thus shared across all functions (methods) of that object.
Two minor points to consider:<li>instead of assigning 0 and 1 to self.show, consider using True and False which are easier to read/understand</li>
<li>instead of using <i>if self.show == 1:</i> consider using <i>if self.show:</i> which is easier to type/read/understand and deals well with the situation where self.show is set to 2, 'a', True, etc.</li> -
Thank you so much!!! That really helped!
-
So when ever I want to use a variable all throughout my code I should make it self.
-
All throughout the <b>class</b>.