Reputation: 31
Hello fine people of Stackoverflow!
I have a problem. I am trying to change an instance variable (which is on it's own a class instance) and for some reason, it changes the same instance variable for all instances of the original class.
here is the code:
#create State class
class State(object):
awake = False
#Set Person Class
class Person(object):
state = State()
#create person instences
jack = Person()
jill = Person()
print(jack.state.awake)
print(jill.state.awake)
#wake jill only
jill.state.awake = True
print("")
print(jack.state.awake)
print(jill.state.awake)
OUTPUT:
False
False
True
True
I am trying to wake jill only.
Upvotes: 0
Views: 33
Reputation: 39
#create State class
class State(object):
def __init__(self):
self.awake = False
#Set Person Class
class Person(object):
def __init__(self):
self.state = State()
#create person instences
jack = Person()
jill = Person()
print(jack.state.awake)
print(jill.state.awake)
#wake jill only
jill.state.awake = True
print("")
print(jack.state.awake)
print(jill.state.awake)
Upvotes: 1
Reputation: 118011
For awake
and state
to be instance variables they'd have to be bound to a self
instance, instead of at the class level. Otherwise class variables are static, in other words share state across all instances of that class.
class State:
def __init__(self):
self.awake = False
class Person:
def __init__(self):
self.state = State()
Then it works as you described
>>> jack = Person()
>>> jill = Person()
>>> jack.state.awake
False
>>> jill.state.awake
False
>>> jill.state.awake = True
>>> jack.state.awake
False
>>> jill.state.awake
True
Upvotes: 1