class blah(object):
def __init__(self):
self.x=5
blahinstance=blah()
def testclass():
blahinstance.x+=1
print blahinstance.x
testclass() #blah will be incremented
print blahinstance.x #the incremented value holds after function exit
"------------------------------------------------------------------------------------"
x=5
def test():
x+=1
print x
print x
test() #fails because ref before assignemnt
So we have read access and modify access to global variables inside a local scope, but obviously attempts at re-assignment will just create a local variable of the same name as the global variable. In the examples above, what is different about referencing the instance attribute blahinstance.x
which is outside of the functions scope? To me these examples are quite similar yet one fails and one does not. We do not have a ref before assignment error with blahinstance.x
despite the fact that this object is in the global scope, similar to the second example of x
.
To clarify - i totally understand the second example, and global vs local scope. What I don't understand is why the first works because it seems similar to the second. Is it because the instance object and it's attribute are mutable, and we have read/modify access to globals in a local scope?