I have a simple socket class: MySocketLib.py ..
import socket
class socklib():
def create_tcp_serversocket(self,port):
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind((socket.gethostname(), port))
serversocket.listen(5)
return serversocket
def send_msg(self, sock, msg, msglen):
... blah blah ...
def recv_msg(self, sock, msglen):
... blah blah ....
My main file is Server.py as follows:
import MySocketLib
class serverclass():
def __init__(self,port):
self.servsock = 0
self.port = port
def run(self):
self.servsock = self.create_tcp_serversocket(self.port)
(clientsock, address) = self.servsock.accept() # ERROR: 'SELF' not defined
... blah blah ...
#############################
### Main startup code
if __name__ == '__main__':
server = serverclass(2000) # server is on port 2000
server.run()
I keep getting the below error:
File "D:\CodeLearn\Server.py", line 14, in serverclass
(clientsock, address) = self.servsock.accept()
NameError: name 'self' is not defined
I can’t seem to get a handle on the concept of “self”. Some times, it seems to be needed and sometimes not. Why would i need to define ‘self’ here when it is a python keyword?
Thanks everyone … it was indeed the tabs and spacing issues. I use eclipse and in preferences I have set “Editor” preferences to use spaces when tabbing.
Don’t use tabs in Python source code. Configure your editor to always use spaces.
selfis not a Python keyword, it’s a convention. It’s the usual name for the “instance” of a class you’re using. Example:When this code runs, the Python runtime will eventually allocate memory for two instances of
Xwhich it will assign toaandbrespectively. If there wasn’t something likeself, you would have to write:And you would get an error because you wrote
b.binstead ofb.v. Moreover, calling methods would be outright ugly:How would you say “access the reference
vwhich was allocated in__init__ofX“?One solution would be to pass the instance reference (the pointer to the memory which was allocated for
X) as a parameter:Everyone would use different names and we would all violate DRY and it would be a mess. So what Python did is:
That said, I have no idea why the code above fails.
selfis obviously defined or the error would already happen in the first line of yourrun()method. So my guess is that you mixed spaces and tabs for indentation and that confuses Python and it sees:Then it would try to evaluate
self.servsock.accept()while it parses the class definition. At that time, there is no instance yet (the class doesn’t exist!) soselfis not available either.Conclusion: Never mix tabs and spaces.