我目前正在尝试写一个ircbot并且卡住了。正如您所看到的,我为ircBot类定义了一个方法connect,它创建了一个套接字对象。我想在sendCmd方法中使用这个对象,这可能吗?
我一直在寻找谷歌和stackoverflow,但一直没能找到解决方案(可能是因为我对Python很新)。任何提示赞赏!
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")
此致
大卫
答案 0 :(得分:3)
技巧是方法的第一个参数,通常在Python中命名为self
。调用方法时,会自动传递此参数。
这是该类的实例 - 因此,如果您执行ircbot.sendCmd(cmd)
,sendCmd
将ircbot
作为self
,那么它可以将自己用作self.sendCmd
如果你想要的话。
您可以向self
添加属性,并将其添加到实例中 - 这意味着connect
对self
,sendCmd
所做的工作也会看到。
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')
答案 1 :(得分:0)
您需要将其分配给可以在connect
之外访问的变量。通常,这是通过创建一个称为成员级别变量的东西来完成的:
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")
答案 2 :(得分:0)
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")