Python编码技术:使用另一种方法作为接口进行系统调用的类方法

问题描述 投票:1回答:1

有没有办法更好地实现我的代码利用python编码技术考虑到我有一些方法都包装一个特定的方法,并添加一些前/后处理?

希望利用python编码技术(思考python装饰器可能有助于清理这一点)来实现下面的类。

我有一个类,它有一个与外部世界接口的方法,并且类中的其他方法用于执行操作并对某些数据进行事前/后处理。

import subprocess as sp


class MyClass():

    def _system_interface(self, command):
        hello = ["echo", "'hello'"]
        start = ["echo", "'start'"]
        stop = ["echo", "'reset'"]
        reset = ["echo", "'reset'"]

        cmd = sp.Popen(locals()[command], stdout=sp.PIPE)
        output = cmd.stdout.readlines()
        print(output)
        return cmd.stdout.readlines()

    def call_one(self):
        # Do some processing
        self._system_interface("hello")

    def call_two(self):
        # Do some processing
        self._system_interface("start")

    def call_three(self):
        # Do some processing
        self._system_interface("stop")

    if __name__ == "__main__":
        c = MyClass()
        c.call_one()
        c.call_two()
        c.call_three()
python python-decorators
1个回答
1
投票

您可以使用在实例化时接受命令的类,并在调用时返回一个装饰器函数,该函数使用从实例化期间给出的命令派生的命令调用Popen

import subprocess as sp

class system_interface:
    def __init__(self, command):
        self.command = command

    def __call__(self, func):
        def wrapper(*args, **kwargs):
            func(*args, **kwargs)
            cmd = sp.Popen(['echo', self.command], stdout=sp.PIPE)
            output = cmd.stdout.readlines()
            print(output)
            return cmd.stdout.readlines()

        return wrapper

class MyClass():
    @system_interface('hello')
    def call_one(self):
        print('one: do some processing')

    @system_interface('start')
    def call_two(self):
        print('two: do some processing')

    @system_interface('stop')
    def call_three(self):
        print('three: do some processing')

if __name__ == "__main__":
    c = MyClass()
    c.call_one()
    c.call_two()
    c.call_three()

这输出:

one: do some processing
[b'hello\n']
two: do some processing
[b'start\n']
three: do some processing
[b'stop\n']
© www.soinside.com 2019 - 2024. All rights reserved.