Skip to content Skip to sidebar Skip to footer

Why Is A Global Dictionary Accessible Inside A Class Whereas A Global Integer Variable Is Not?

I have declared a dictionary globally and a variable as well. Now, when accessing both in a class, I can access the dictionary but for accessing the other variable, I get the Unbou

Solution 1:

Short:

You are trying to change the value of curr_length with curr_length = len(str_) inside a function which looks for a local curr_length variable, and can't find it. It needs the line global curr_length to know that it's a global variable.

As far as why you're wondering as to why a dict object does not need global memoized line, you should read the answer to: Global dictionaries don't need keyword global to modify them? or Why is the global keyword not required in this case?

EXPLANATION:

In Python, a variable declared outside of the function or in global scope is known as global variable. This means, global variable can be accessed inside or outside of the function.

Let's see an example on how a global variable is created in Python.

x = "global"deffoo():
    print("x inside :", x)

foo()
print("x outside:", x)

When we run the code, the will output be:

x inside : global
x outside: global

In above code, we created x as a global variable and defined a foo() to print the global variable x. Finally, we call the foo() which will print the value of x.

What if you want to change value of x inside a function?

def foo():
    x = x * 2print(x)
foo()

When we run the code, the will output be:

UnboundLocalError: local variable 'x' referenced before assignment

The output shows an error because Python treats x as a local variable and x is also not defined inside foo().

To make this work we use global keyword

Post a Comment for "Why Is A Global Dictionary Accessible Inside A Class Whereas A Global Integer Variable Is Not?"