Reply
Thread Tools
Posts: 6 | Thanked: 0 times | Joined on Feb 2010
#1
Hey everyone,
I'm a beginner Python and PyGTK developer so sorry for the stupid question.I have a class named Client which is meant to send data to a server via UDP socket. here is a snippet of the

Code:
class Client:
    # Set the socket parameters
    addr = ('','')
    UDPSock = socket(AF_INET,SOCK_DGRAM)

    # callback for getting the IP address
    def connect_callback(self, widget, entry):
  	hostName = entry.get_text()
    	addr = (hostName,21567)
   
    #callback to send the message in the testfield
    def send_mesg_callback(self, widget, textfield):
	t_msg = textfield.get_buffer()
	if(UDPSock.sendto(t_msg,addr)):
		print "Sending message '",t_msg,"'....."
...
I get undeclared global variable error for addr and UDPSock.
But I can't access my global variables it gives me an error, even when I put a 'self.' infront of the global variables for example infront of UDPSOCK. what am i doing wrong here?


-Thank you
 
Posts: 19 | Thanked: 7 times | Joined on Jan 2010 @ dallas, tx usa
#2
Instead of defining it there, do it in the constructor (__init__ function).


class SomeClass(object):

def __init__(self):
# Set the socket parameters
self.addr = ('','')
self.UDPSock = socket(AF_INET,SOCK_DGRAM)


this will still be available to all your methods inside the class. You will have to prefix it with "self" everywhere you use it, since you're saying "this instance of this class owns this variable", not "This class as a whole has this single instance of a variable"
 
andrei1089's Avatar
Posts: 81 | Thanked: 109 times | Joined on Apr 2009 @ Brasov/Cluj, Romania
#3
Originally Posted by armen_shlang View Post
Hey everyone,
I'm a beginner Python and PyGTK developer so sorry for the stupid question.I have a class named Client which is meant to send data to a server via UDP socket. here is a snippet of the

Code:
class Client:
    # Set the socket parameters
    addr = ('','')
    UDPSock = socket(AF_INET,SOCK_DGRAM)

    # callback for getting the IP address
    def connect_callback(self, widget, entry):
  	hostName = entry.get_text()
    	addr = (hostName,21567)
   
    #callback to send the message in the testfield
    def send_mesg_callback(self, widget, textfield):
	t_msg = textfield.get_buffer()
	if(UDPSock.sendto(t_msg,addr)):
		print "Sending message '",t_msg,"'....."
...
I get undeclared global variable error for addr and UDPSock.
But I can't access my global variables it gives me an error, even when I put a 'self.' infront of the global variables for example infront of UDPSOCK. what am i doing wrong here?


-Thank you
you should use self when trying to access UDPSock in this line if(UDPSock.sendto(t_msg,addr)).
 
Reply

Thread Tools

 
Forum Jump


All times are GMT. The time now is 09:57.