[英]How to read instance variables from another file without instantiating the class?
I'm relatively new to Python and I'm having some trouble importing a variable to use it in another class. 我是Python的新手,我在导入变量时遇到了一些问题,无法在另一个类中使用它。 I did look at several other questions on this topic and tried to make it work, but it seems the way I set up this program early on might be the problem. 我确实看了几个关于这个主题的其他问题,并尝试使它工作,但似乎我早期设置这个程序的方式可能是问题。 I'll simplify what's going on so there's less to read... 我将简化发生的事情,因此阅读的内容较少......
Server.py: 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: 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
In this example, I'm trying to reference the variable "test" from the server instance of Server. 在这个例子中,我试图从Server的服务器实例引用变量“test”。 It's worth noting that this DOES WORK if I put both classes in the same file and then remove the if statement at the end of it...but I'd rather not have one file that long :) 值得注意的是,如果我将两个类放在同一个文件中,然后删除它末尾的if语句,那么这就行了......但我宁愿没有一个文件那么久:)
Since these are in separate files, I can't get the instance variables from "server" without removing that if statement in Server.py. 由于这些文件位于不同的文件中,因此无法在Server.py中删除if语句而无法从“server”获取实例变量。 When I do remove it, I get socket errors because of other stuff I'm doing...I need to make it so that there's only ever one server object (and that its class is only "called" once), but it'd be really handy to be able to reference those instance variables without passing them in to my Game class every time it runs... 当我删除它时,由于我正在做的其他事情,我得到套接字错误...我需要做到这一点,以便只有一个服务器对象(并且它的类只被“调用”一次),但它' d非常方便能够引用这些实例变量,而不是每次运行时都将它们传递给我的Game类...
Part of this is definitely my fault in that I set my program up wrong...but I'm too far in to start that over. 部分原因绝对是我的错,因为我把我的程序设置错了......但是我太过分了。 Is there any way I can take this sort of setup and read in those variables? 有什么方法可以采取这种设置并读取这些变量?
First, test
exists as an instance variable, so you'll need to pass an instance of Server
to your game loop: 首先, test
作为实例变量存在,因此您需要将Server
的实例传递给游戏循环:
class Server:
def serve(self):
# Client processing, etc.
self.game.game_loop(self)
Next, you can find test
in game_loop
by looking in the passed-in instance: 接下来,您可以通过查看传入的实例在game_loop
找到test
:
class Game:
def game_loop(self, server):
print server.test
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.