![](/img/trans.png)
[英]Is it possible to modify variables in different class from within App() without instantiating new instance of class
[英]How to read instance variables from another file without instantiating the class?
我是Python的新手,我在導入變量時遇到了一些問題,無法在另一個類中使用它。 我確實看了幾個關於這個主題的其他問題,並嘗試使它工作,但似乎我早期設置這個程序的方式可能是問題。 我將簡化發生的事情,因此閱讀的內容較少......
Server.py:
import Game
class Server():
def __init__(self):
# Server connection details here
self.test = 5
self.game = Game()
def serve(self):
# Client processing, etc.
self.game.game_loop()
if __name__ == "__main__":
server = Server()
server.serve()
Game.py:
class Game():
def __init__(self):
# Other variables...
def game_loop(self):
# To reference server's instance variables
from Server import server
print test
在這個例子中,我試圖從Server的服務器實例引用變量“test”。 值得注意的是,如果我將兩個類放在同一個文件中,然后刪除它末尾的if語句,那么這就行了......但我寧願沒有一個文件那么久:)
由於這些文件位於不同的文件中,因此無法在Server.py中刪除if語句而無法從“server”獲取實例變量。 當我刪除它時,由於我正在做的其他事情,我得到套接字錯誤...我需要做到這一點,以便只有一個服務器對象(並且它的類只被“調用”一次),但它' d非常方便能夠引用這些實例變量,而不是每次運行時都將它們傳遞給我的Game類...
部分原因絕對是我的錯,因為我把我的程序設置錯了......但是我太過分了。 有什么方法可以采取這種設置並讀取這些變量?
首先, test
作為實例變量存在,因此您需要將Server
的實例傳遞給游戲循環:
class Server:
def serve(self):
# Client processing, etc.
self.game.game_loop(self)
接下來,您可以通過查看傳入的實例在game_loop
找到test
:
class Game:
def game_loop(self, server):
print server.test
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.