How can I update an instance variable based on another instance? Is there a way to get a many-to-many dependency between objects in Python?
- Deptest is a class which can be either ONLINE or OFFLINE, and it has a dictionary instance variable called "Dependencies" which is setup like so {"CONDITION STRING":instance.instancevariable == value}
- S1 and S2 are instances of Deptest
- S1 requires S2 to be ONLINE in order to be made ONLINE
- If UP is pressed, S1's dependencies are checked. If they are met, S1 is now online.
- If DOWN is pressed, S2's dependencies are checked. Since it has none, it is made online.
What happens: - S1's definition for S2 being online is never changed from its initial value. I'm not sure why, because it is called to be updated every cycle.
NOTE: S1 may be dependent on more than one attribute from s2, or may even be dependent on an S3, s4, basically an arbitrary number of dependencies.
This is what I've tried so far:
import pygame
from pygame.locals import *
pygame.init()
class deptest():
def __init__(self,name):
self.name = name
self.status = ""
self.dependencies = {}
def updatestatus(self):
if self.checkdependencies():
self.status = "ONLINE"
else:
self.status = "OFFLINE"
def checkdependencies(self):
if self.dependencies:
for dv in self.dependencies.values():
dv=dv
if not all(dv for dv in self.dependencies.values()):
print("{}: Still waiting".format(self.name))
for ds,dv in self.dependencies.items():
print("{}: {}".format(ds,dv))
return False
else:
print("{}: Good to go".format(self.name))
return True
else:
print("{}: Good to go".format(self.name))
return True
s1 = deptest("s1")
s2 = deptest("s2")
s1.dependencies = {"S2 ONLINE":s2.status == "ONLINE"}
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == KEYDOWN:
if event.key == pygame.K_UP:
print("PRESSED UP")
if s1.checkdependencies():
s1.status = "ONLINE"
if event.key == pygame.K_DOWN:
print("PRESSED DOWN")
if s2.checkdependencies():
s2.status = "ONLINE"
for s in [s1,s2]:
s.updatestatus()
pygame.quit()
sys.exit()
Is this a misunderstanding on my part about how classes and instances work?
EDIT: Looking around a bit, I think this might be the 'Observer' design pattern. EDIT: Or maybe 'Mediator'-- I'm not really sure.