A question regarding a class and it's methods
I am currently trying to write an ircbot and have gotten stuck. As you can see I define a method for the ircBot class, connect, which creates a socket object. I want to use this object in the sendCmd method, is this possible?
I have been looking around google and stackoverflow but have not been able to work out a solution(probably because I'm rather new to Python). Any hints appreciated!
import socket
import sys
import os
class ircBot:
def sendCmd(self开发者_运维问答, cmd):
SEND_TEXT_ON_OPEN_SOCKET
def connect(self, server, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
c = s.connect_ex((server, port))
if c == 111:
print("Error: " + os.strerror(c))
sys.exit(1)
print("Making connection to " + server + "\n")
Regards,
David
The trick is the first parameter to the methods, normally named self
in Python. When you call the methods, this parameter is automatically passed.
It's the instance of the class -- so if you do ircbot.sendCmd(cmd)
, sendCmd
gets ircbot
as self
, and so it could use itself as self.sendCmd
if you wanted.
You can add attributes to self
, and it adds them to the instance -- this means that what connect
does to self
, sendCmd
will see as well.
import socket
import sys
import os
class IrcBot: # You should consider doing 'class IrcBot(object):'
# if you're on Python 2, so it's a new-style class
def sendCmd(self, cmd):
# use self.s here
SEND_TEXT_ON_OPEN_SOCKET
def connect(self, server, port):
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
c = self.s.connect_ex((server, port))
if c == 111: # is this the only return code that matters?
# I don't know, you might want to check for others
print("Error: " + os.strerror(c))
sys.exit(1)
print("Making connection to " + server + "\n")
ircbot = IrcBot()
ircbot.connect('localhost', 6667)
ircbot.sendCmd('yourcmd')
You need to assign it to a variable which can be accessed outside of connect
. Normally this is done by creating something called a member level variable:
class ircBot:
def sendCmd(self, cmd):
# SEND_TEXT_ON_OPEN_SOCKET
s.doSomething()
def connect(self, server, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
c = s.connect_ex((server, port))
if c == 111:
print("Error: " + os.strerror(c))
# this should probably simply throw an exception. No need to take teh
# whole system down on socket connection failure.
sys.exit(1)
self.s = s
# I moved this up a level because you could never get to it in the
# if statement -- sys.exit leaves the application!
print("Making connection to " + server + "\n")
import socket
import sys
import os
class ircBot:
def sendCmd(self, cmd):
if self.s is None:
raise "Not connected to a server"
self.s.send(cmd)
def connect(self, server, port):
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
c = self.s.connect_ex((server, port))
if c == 111:
print("Error: " + os.strerror(c))
sys.exit(1)
print("Making connection to " + server + "\n")
精彩评论