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
4
  • 2
    A string won’t automatically update just because a number you used to make it changed. Commented Apr 6, 2020 at 2:52
  • Yes, that is why I am asking for help. Commented Apr 6, 2020 at 2:53
  • 1
    Right, this has nothing to do with global variables, which you shouldn't be using in the first place Commented Apr 6, 2020 at 2:59
  • 1
    Instead of global variables you should use instance attributes in your class. Commented Apr 6, 2020 at 3:00

1 Answer 1

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.

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

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.