I am struggling to understand why a local function in Python 3 can seemingly modify global object attributes but not variables. If we consider object attributes to be variables attached to objects, this behavior appears very inconsistent and I cannot understand why the language behaves in this way.
- We can create some class and use a function to modify an attribute of that class without anything like a global declaration of that attribute.
If we have some code:
class Integer:
def __init__(self, number):
self.value = number
n = Integer(20)
print(n.value) # display value at initialization
def increase_n():
n.value += 1
increase_n()
print(n.value) # display value after calling increase_n
Running this code would result in the following output:
20
21
- We cannot do the same with a variable. An explicit global declaration must be used.
If we have some code:
k = 6
print(k) # display value after assignment
def increase_k():
global k
k += 2
increase_k()
print(k) # display value after calling increase_k
Running the above code results in:
6
8
Note that foregoing the global declaration for the second example would result in an error.
I am hoping someone can enlighten me. I am sure there must be some fundamental misunderstanding on my part. Why are variables and attributes treated so differently? Why is this good/bad?