alwbtc
alwbtc

Reputation: 29445

Changing a variable's value inside a class in python

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?

Upvotes: 0

Views: 63

Answers (1)

David Heffernan
David Heffernan

Reputation: 612854

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.

Upvotes: 2

Related Questions