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?
asked Apr 16, 2014 at 10:39
alwbtc
29.8k63 gold badges142 silver badges197 bronze badges
-
2You can't. Integers are immutable.anon582847382– anon5828473822014年04月16日 10:40:05 +00:00Commented Apr 16, 2014 at 10:40
1 Answer 1
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.
answered Apr 16, 2014 at 10:41
David Heffernan
616k46 gold badges1.1k silver badges1.5k bronze badges
Sign up to request clarification or add additional context in comments.
11 Comments
alwbtc
Ok, what if it is not a int but a bool?
David Heffernan
If you are interested in booleans, why did you ask about
int. But as it happens, Python booleans are also immutable.alwbtc
I didnt know it would matter.
anon582847382
@alwbtc Booleans are immutable as well.
Samy Arous
you can use a mutable object like a list (even if it contains one single int) or a custom object.
|
lang-py