如何避免类函数中的代码重复?

时间:2019-12-09 08:11:20

标签: python oop

我有一个项目,该项目解析来自pushbullet的推送,并根据输入执行功能。这是我的Push课:

class Push():
    def __init__(self, push):
        r = push
        self.iden = r['iden']
        self.type = r['type']
        if self.type == 'note':
            self.body = r['body']
    def register(self):
        self.is_processed = False
        push_log.append_iden(self.iden)
    def expire(self):
        self.is_processed = True
        push_log.update_status(self.iden)
    def is_command(self):
        if '!' in self.body:
            return True
        else:
            return False

因此,当程序检测到命令时,它将运行另一组类函数:

    def process_command(self):
        if 'shoot' in self.body:
            try:
                shoot()
                self.expire()
            except:
                self.expire()
        elif 'getip' in self.body:
            try:
                get_ip()
                self.expire()
            except:
                self.expire()
        elif 'wol' in self.body:
            try:
                ip = self.body.split(" ")[1]
                wake_on_lan(ip)
                self.expire()
            except:
                self.expire()

请注意,在类中未定义get_ip(),wake_on_lan(ip)和Shoot()。但是我想尽可能避免代码重复。因此,我试图重新编写process_command(self)函数。我特别想避免重复self.expire()try / except子句。

 def process_command(self):
        command_list = ['shoot', 'getip', 'wol']
        for command in command_list:
            if command in self.body:
                try:
                        # do something 
                        self.expire()
                    else:
                        self.expire()
                except:
                    self.expire

部分解决了我的问题。这是理智的方法吗?我想通过提供(输入命令,要执行的功能)元组来改进它。

command_list = [('shoot', shoot()), ('getip', get_ip()), ('wol', wake_on_lan(self.body.split(" ")[1]))]

但是功能随时随地执行。有更好的方法吗?

编辑

基于响应,这是编辑后的process_command。谢谢@ deceze,@ Jean和@Thierry。

    def process_command(self):
        command_count = 0
        command_dict = {
            'shoot': shoot,
            'getip': get_ip,
            'wol': wake_on_lan
        }
        for command in command_dict.keys():
            if command in self.body:
                try:
                    if command_count < 2:
                        # do something

                    else:
                        # do something else
                except:
                    # raise/catch exception
                finally:
                    self.expire()

1 个答案:

答案 0 :(得分:3)

您的问题有很多东西。我要讲的是我唯一清楚的部分:

  

我特别想避免重复self.expire()try / except子句。

您的self.expire()实际上只需要在finally:块中出现一次,就像这样:

try:
    # do something 
except:
    # Handle exceptions, perhaps re-raise some exceptions
finally:
    self.expire()  # Will run no matter what