Griffin
Griffin

Reputation: 644

Sharing variables between two classes in Python

I felt like working on my network programming, threading and OOP skills. I've encountered a problem though. I have a class named IRC and a class named Pong. I want to use IRC to do stuff like connecting to the server, sending messages, etc. I want to use Pong as a thread in the background which checks for a message containing "PING".

class IRC:
    def Connect(self):
        try:
            HOST = sys.argv[1]
            PORT = sys.argv[2]
        except IndexError:
            print "Usage: "+sys.argv[0]+" [server] [port]\n"
            sys.exit(1)
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((HOST, PORT))

class Pong(threading.Thread):
    def Pong(self):
        while 1:
            IRC.s.send("Test") # IRC has no attribute 's'

Keep in mind that the code above is simplified and only for testing purposes, my question is how I can use variables in one class from another class. The variable s is declared and defined in IRC, but is needed in Pong too. The interpreter complains that class IRC has no attribute 's' (I've tried calling Connect() first with a sample variable to see if it works, it doesn't).

How do I solve this? I'm new when it comes to threading and object orientation.

Thanks in advance!

Upvotes: 1

Views: 2721

Answers (1)

Mud
Mud

Reputation: 72

You'll need to call an instance of the IRC class which you can pass to the PONG constructor:

class IRC:
    def Connect(self):
        try:
            HOST = sys.argv[1]
            PORT = sys.argv[2]
        except IndexError:
            print "Usage: "+sys.argv[0]+" [server] [port]\n"
            sys.exit(1)
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.connect((HOST, PORT))

class Pong(threading.Thread):
    def __init__(self,ircclass):
        self.myirc = ircclass
    def Pong(self):
        while 1:
            self.myirc.s.send("Test")

gIRC = IRC
gIRC.connect()
myPong = Pong(gIRC)

etc.

Upvotes: 3

Related Questions