0

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

3
  • 1
    Are you sure your code is correct? The function in the first code requires an argument and yet you didn't provide any Commented Aug 15, 2020 at 3:19
  • 2
    ... similarly, __init__ requires one positional argument. Commented Aug 15, 2020 at 3:21
  • You are passing an object in both cases, there is no such thing as "passing a variable". However, in the first case, the object is immutable, it is an int. In the second case, it is not immutable, it is an instance of your custom class. That's the only difference here. The answer you accepted is completely incorrect. There is only a single evaluation strategy in Python, and it is neither call by value nor call by reference Commented Aug 15, 2020 at 6:23

1 Answer 1

2

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.

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

1 Comment

Absolutely incorrect. This answer is confused in two ways. Python only has a single evaluation strategy which is neither call by value nor call by reference. Secondly, there is no distinction between passing "a variable" and passing an object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.