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

2024-10-17 00:26:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个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

抱歉,如果这不是很清楚,但也许它表明a)我正在努力实现和b)我做错了。你知道吗


Tags: theself脚本消息message客户机heredef
1条回答
网友
1楼 · 发布于 2024-10-17 00:26:08

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
       ...

相关问题 更多 >