-2

I have some code that's structured like so.

def function():
    test = myClass()
    var = 1
    running = True

    while running:
        if var == 1:
            print(1)
            test.update(var)
        if var == 2:
            print(2)

class myClass:
    def update(self, var):
        var = 2

Essentially the code should print '1' only once and then print an indefinite number of '2's as the value of var is changed from '1' to '2' in the update method. However, it just prints loads of '1's.

How do you change the value of a variable found in a function by using a class's method in that function?

I've also tried with global variables and it doesn't work (and I've heard is generally frowned upon).

PRyan
  • 3
  • 1
  • 2
    It won't update the variable from the outer scope. If you want to keep it updated make it a member of the class. – Paul Rooney Apr 25 '18 at 22:24
  • You cannot pass variables around in Python. See https://nedbatchelder.com/text/names.html – user2357112 Apr 25 '18 at 22:30
  • 2
    Possible duplicate of [How do I pass a variable by reference](https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference) – Jeff Learman Apr 25 '18 at 22:36

1 Answers1

0

Return the new value in the update method and assign it in the call to the variable.

...
while running:
  if var == 1:
    print(var)
    var = test.update(var)
...

class myClass:
  def update(self, _var): # _var is removable unless you will use it
    return 2
Paul Rooney
  • 20,879
  • 9
  • 40
  • 61