3

I am trying to get rid of my global variables but I am not sucessful doing so.

In this case I let the user assign coordinates when I run the program. From those coordinates we are starting to sail a boat (within a matrix) meaning that the functions I have that control movement need to have access to these coordinates from the input function. Also the movement functions need to assign new values to the coordinates.

koordx = 0
koordy = 0

distancetraveled = 0

def input ():
    global koordx
    global koordy


    koordx = int(input ("Assign Y coordinate)"))
    koordy = int(input("Assign Y coordinate"))

       ..... etc 

This is example of movement, changing the coordinates.

def north ():
    global distancetraveled
    distancetraveled += 2
    global koordy
    koordy -= 1


def northeast():
    global distancetraveled
    distancetraveled += 2
    global koordx
    koordx += 1
    global koordy
    koordy -= 1

def movement():
    if... . .. :
       northeast() etc... #moves northeast

input()

movement()

This is just an example, I have some more functions that need to access these coordinates and their values. How can I in a smooth way get rid of my global variables?

This is just a section of my code which I modified to make it more understandable what I need help with.

Any hints would be greatly appreciated.

1
  • Wow, this came out quite a mess, but I hope you understand that the code beside the function definition are supposed to be inside the function. Thank you! Commented Dec 1, 2013 at 14:19

1 Answer 1

7

You could create a Boat class, and encapsulate the coordinates and distance within instances of Boat:

class Boat:
    def __init__(self, x, y, dist=0):
         self.x = x
         self.y = y
         self.dist=dist

Then you can either create functions that operate on Boats, and modify those variables, or you can create methods within the Boat class that operate on the variables (which is a more object-oriented way of doing this, and encapsulates the state better)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, and a huge thanks to the guy who edited my post! I actually tried a solution like yours before I started this thread. I did not quite succeed in changing the variables within the constructor since if I assign values within the methods they are local to that method. Would you mind explaining further?

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.