0

I have a variable:

var_1 = 5

I pass it to a class:

class x():
    def __init__(self, val):
        self.class_var_1 = val

object_1 = x(var_1)

I want to change var_1's value using class x, but it won't change

object_1.class_var_1 = 3

print var_1
5

var_1 isn't copied to object_1.class_var_1 with a reference to var_1.

How do I change var_1's value by changing object_1.class_var_1's value?

1
  • 2
    You can't. Integers are immutable. Commented Apr 16, 2014 at 10:40

1 Answer 1

2

Python int is immutable. The object can never change its value. Thus you need to re-bind the name to a different object. You'll need code like this:

var_1 = ...

Substitute whatever you like on the right hand side.

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

11 Comments

Ok, what if it is not a int but a bool?
If you are interested in booleans, why did you ask about int. But as it happens, Python booleans are also immutable.
I didnt know it would matter.
@alwbtc Booleans are immutable as well.
you can use a mutable object like a list (even if it contains one single int) or a custom 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.