0

I'm working on a Python game intended for young programmers. I have a parent class (parent.py in this example) that hides a bunch of complexity. The young programmer works with a template (child.py in this example) where they create code for three functions which override methods in the parent class. The problem I'm having is that global variables defined along with the child class appear to work inconsistently.

I've stripped the parent.py and child.py files down to a minimal example that exhibits the problem. The 'mySpeed' global defined in child.py works as expected in the first call to mySetup, but errors out in the call to myMove.

Here's the parent.py file:

class parent():

  def setup(self):
    print ("Empty setup")

  def ping(self):
    print ("Empty ping")

  def move(self):
    print ("Empty move")

  def play(self):
    self.setup()
    counter = 0
    while counter < 50:
      self.move()
      counter += 1
      if counter == 10:
        self.ping()

Here's the child.py file:

import parent

# Define any global variables here
mySpeed = 5

# Things that you want to happen when the game starts
def mySetup():
  print("Setup speed", mySpeed)

# Things you want to do every move
def myMove():
  mySpeed += 1
  print("Move speed", mySpeed)

# What you want to do if an enemy scans you
def myPing():
  mySpeed += 10
  print("Ping speed", mySpeed)

# Template code below this point - do not modify.
# Define child class
class child(parent.parent):

  # Map our three functions to parent class
  def setup(self):
    mySetup()

  def move(self):
    myMove()

  def ping(self):
    myPing()

myChild = child()

myChild.play()

Finally, here are the results. Note that the message in the setup() function works as expected.

# python3 child.py
Setup speed 5
Traceback (most recent call last):
  File "child.py", line 36, in <module>
    myChild.play()
  File "/home/xxx/parent.py", line 17, in play
    self.move()
  File "child.py", line 29, in move
    myMove()
  File "child.py", line 12, in myMove
    mySpeed += 1
UnboundLocalError: local variable 'mySpeed' referenced before assignment
pbft
  • 41
  • 5

0 Answers0