CarsonH26
CarsonH26

Reputation: 27

Problems with global variables in Python

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

Upvotes: 1

Views: 82

Answers (1)

l_l_l_l_l_l_l_l
l_l_l_l_l_l_l_l

Reputation: 538

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.

Upvotes: 2

Related Questions