1

I am attempting to transfer a global integer and string between functions. The integer seems to be transferring fine but the string is not. The string contains the global integer in it. Even after I change the global integer in my second function the string containing the integer doesn't seem to update. Any help would be greatly appreciated.

num=1
num_str = ''

class Class(object):

    def Function1(self):
        global num
        global num_str
        num_str = ("number " + str(num))
        print(num)
        print(num_str)
        self.Function2()

    def Function2(self):
        global num
        global num_str
        num += 1
        print(num)
        print(num_str)


Class().Function1()

My output is

1
number 1
2
number 1

Process finished with exit code 0
CarsonH26
  • 27
  • 5

1 Answers1

2

If you'd like the string to update every time the number is updated, you don't actually want a string; you want a function/lambda that returns a string. Here's an example:

num=1
num_str = None

class Class(object):
    def Function1(self):
        global num, num_str
        num_str = lambda: f'number {num}'
        print(num)
        print(num_str())
        self.Function2()

    def Function2(self):
        global num, num_str
        num += 1
        print(num)
        print(num_str())


Class().Function1()

Output:

1
number 1
2
number 2

Edit: also, keep in mind globals are discouraged, though they're irrelevant for this question.

l_l_l_l_l_l_l_l
  • 528
  • 2
  • 8
  • If you plan to run your code on the cloud you have one further reason to avoid using globals. Various servers may be active running different functions and it is unlikely that all of them will acknowledge your global variable – Al Martins Apr 21 '20 at 18:37