从对象调用父类方法的最佳方法

时间:2014-04-04 15:51:23

标签: python

我创建了一个python脚本来创建一个IRC客户端。

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

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

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

对不起,如果不是很清楚,但也许它表明了a)我想要实现的目标和b)我做错了。

1 个答案:

答案 0 :(得分: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
       ...