Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to read instance variables from another file without instantiating the class?
    primarykey
    data
    text
    <p>I'm relatively new to Python and I'm having some trouble importing a variable to use it in another class. 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...</p> <p>Server.py:</p> <pre><code>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() </code></pre> <p>Game.py:</p> <pre><code>class Game(): def __init__(self): # Other variables... def game_loop(self): # To reference server's instance variables from Server import server print test </code></pre> <p>In this example, I'm trying to reference the variable "test" from the server instance of Server. 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 :)</p> <p>Since these are in separate files, I can't get the instance variables from "server" without removing that if statement in Server.py. 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...</p> <p>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?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload