2014-04-04 124 views
0

我创建了一个python脚本来创建一个IRC客户端。从对象中调用父类方法的最佳方法

我现在想给它添加一个聊天机器人功能。

因此,我的IRC客户端的python脚本有很多方法,并且看起来相当庞大,所以我想也许最好创建一个chatbot对象,它可以从IRC客户端读取消息事件并发送适当的消息。我正在以正确的方式思考这个问题?

class IRCClient: 
#client code 
myGreetingBot = GreetingBot() 


def SendToIRC(self, message): 
    # send code implemented here 
    # getting here from the created object is a problem 

while 1: 
    # this main loop continously checks a readbuffer for messages and puts them into a buffer 
    #event driven method calling with IRCClient 
    if ("JOIN" == buffer[1]): 
     myGreetingBot.process(message) 


class GreetingBot(): 
    def process(): 
     #getting here isn't a problem 
     self.SendMessage() 

    def SendMessage(): 
     # here I want to call the SendToIRC() function of the class that created this object 

很抱歉,如果不是很清楚,但也许它显示了)我想实现和b)我做错了。

+1

这很难说,你想用碎缩进做什么。将代码粘贴回来,然后选择它并按下[编辑]工具栏上的[{}'按钮以缩进所有适当的4个空格 – mhlester

+0

代码将不会运行,我只是在我考虑问题时才写它。我真的只是要求最好的方式来扩展我的基类的funcionality。也许我只需要阅读更多关于python的继承。 – user3406725

+0

虽然我明白你的意思,但我不是父类。您需要将客户端传递给GreetingBot()的构造函数(或adda属性并设置它)并将其存储在成员中,然后您可以通过该成员调用其上的任何方法 –

回答

0

IRCClient不是GreetingBot的父亲,反之亦然。所有你拥有的是其中包含的另一个

一个实例来实现亚型基因多态性与有GreetingBot是一个子类的IRCClient一类,你需要从父类扩展,像这样:

class IRCClient: 
    # write all the standard functions for an IRCClient.. Should be able to perform unaware of GreetingBot type 
    ... 

class GreetingBot(IRCClient): 
    # GreetingBot is extending all of IRCClient's attributes, 
    # meaning you can add GreetingBot features while using any IRCClient function/variable 
    ... 

至于标题“从对象中调用父类的方法的最佳方式”,..如果GreetingBot是IRCClient的子项,则可以从GreetingBot实例调用每个IRCClient函数。如果你想却更代码添加到函数(例如__init__),你可以做这样的事情:

class IRCClient: 
    def __init__(self): 
     # do IRCClient stuff 
     ... 

class GreetingBot(IRCClient): 
    def __init__(self): 
     # call parent initialize first 
     super(GreetingBot, self).__init__() 
     # now do GreetingBot stuff 
     ...