Reputation: 79
Here's what I don't understand, if I made a function that would change the value of a variable, this would only save it in the function, so it won't change the global variable.
var = 10
def change_var(variable):
variable += 1
change_var(var)
print(var)
________________________
10
However, when I use the variable of a object (I'm not sure what this is called), it works completely fine. This just doesn't makes sense to me that one works but the other doesn't. This is what I mean
class foo():
def __init__(self, var):
self.var = var
object_ = foo(10)
def change_var(object_):
object_.var += 1
change_var(object_)
print(object_.var)
________________________
11
I want an explanation on why one works but not the other
Upvotes: 0
Views: 847
Reputation: 6395
Python passes variables by Value, but objects by Reference.
So if you modify a variable, you modify your local copy, not the original; if you modify an object, you modify the original.
Upvotes: 2