Forum Archive

The importance of .self

Elden12360

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

ccc

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:

  • instead of assigning 0 and 1 to self.show, consider using True and False which are easier to read/understand
  • instead of using if self.show == 1: consider using if self.show: which is easier to type/read/understand and deals well with the situation where self.show is set to 2, 'a', True, etc.
  • Elden12360

    Thank you so much!!! That really helped!

    Elden12360

    So when ever I want to use a variable all throughout my code I should make it self.

    ccc

    All throughout the class.