![](/img/trans.png)
[英]How to access class method and class variable from a class to another class's instance method in Python?
[英]Python dependencies: class method to access another instance's variable
如何基於另一個實例更新實例變量? 有沒有辦法在Python中的對象之間獲得多對多依賴關系?
發生的情況:-S1對於S2在線的定義永遠不會從其初始值改變。 我不確定為什么,因為它被稱為在每個周期進行更新。
注意:S1可能依賴於s2中的多個屬性,甚至可能依賴於S3,s4,基本上是任意數量的依賴關系。
到目前為止,這是我嘗試過的:
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()
我對類和實例的工作方式是否有誤解?
編輯:環顧四周,我認為這可能是“觀察者”設計模式。 編輯:或者也許是“調解人”-我不太確定。
有很多更好的方法,但是根據您在注釋中的回答,一種方法是不使用字典作為依賴關系,而是使用類似列表的方法,並使用一種方法將依賴關系填充到字典中,然后checkstatus
檢查活動狀態,而不是添加狀態。
將此添加到您的班級:
def __init__(self, name):
... ## all the other stuff
self.dependencies = []
def add_dependency(self, dependency):
self.dependencies.append(dependency)
並檢查依賴項:
def checkdependencies(self):
if self.dependencies:
if all(s.status for s in self.dependencies):
return True
else:
...
並添加依賴項:
s1 = deptest('s1')
s2 = deptest('s2')
s1.add_dependency(s2)
... ## do the same check that you are doing here.
首先要了解的是,您沒有在字典中捕獲對表達式的某種引用……您只是在捕獲當前值。 看看這是否有助於理解這一點:
>>> a = "not ready"
>>> dependencies = {"a": a == "ready"}
>>> dependencies
{'a': False}
>>> a = "ready"
>>> dependencies
{'a': False}
請注意,更改的值a
不改變在字典中的價值。
有幾種方法可以實現您的目標,但是我認為最適合您的用例的方法是存儲函數並在每次我們要檢查值時執行它:
>>> a = "not ready"
>>> dependencies = {"a": lambda: a == "ready"}
>>> dependencies
{'a': <function <lambda> at 0x10fc0cf28>}
>>> dependencies["a"]()
False
>>> a = "ready"
>>> dependencies["a"]()
True
在您的示例中,您將執行以下操作來設置依賴項:
s1.dependencies = {"S2 ONLINE": lambda: s2.status == "ONLINE"}
然后,您需要調用每個函數來檢查依賴項:
if not all(f() for f in self.dependencies.values()):
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.