Declaring and changing class instances inside another class

33 views Asked by At

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.

2

There are 2 answers

0
Cory Kramer On

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
0
Naga Saideep Lanka On
#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)