将自定义函数添加到Python中的现有类

时间:2018-08-22 02:17:26

标签: python

让我们说我有一个Python程序,它是一个黑匣子,其作用类似于处理器。它读取带有一些指令名称的文本文件,解析该文件并从指令类中调用函数。我要允许用户在另一个文件中创建新功能,并允许处理器通过指令类调用这些功能。

示例处理器代码(无法更改):

from instructions import *

instr = Instructions()
code = []
with open('program.txt') as f:
    code = f.readlines()

for line in code:
    command, args = line.split()
    # reads "command arg" and calls "instr.command(arg)"
    string_exec = 'instr.{}({})'.format(command, args)
    eval(string_exec)

示例说明。py:

class Instructions:
    def show(self, arg):
        print(arg, end='')

处理器读取以打印“ Hello”的“ program.txt”示例:

show 'H'
show 'e'
show 'l'
show 'l'
show 'o'
show '\n'

我希望能够从用户那里读取带有新指令的文件,并能够在处理器中执行它们。

也使用说明的用户功能示例:

def print_line(self, args):
    for arg in args:
        instr.show(arg)
    instr.show('\n')

我想以某种方式将用户功能合并到Intructions类中,以便处理器能够运行以下“ program.txt”:

print_line 'Hello'

简而言之,我想将指令功能分为两个文件,一个具有一些基本的“固定”指令,另一个具有用户定义的“动态”功能。最后,我想在指令类中加载这两个函数。

1 个答案:

答案 0 :(得分:2)

instructions.py如下:

class Instructions:
    def __init__(self):
        self._add_user_function()

    def add(self, a, b):
        return a + b

    def _add_user_function(self):
        import os
        if not os.path.exists('user_instructions.py'):
            return
        from user_instructions import UserInstructions
        self._user_instrucs = UserInstructions(self)
        for prop in dir(self._user_instrucs):
            if prop.startswith('_'):
                continue
            prop_type = type(eval("UserInstructions.%s" % prop))
            if str(prop_type).find("instancemethod") < 0:
                continue
            func_str = "def instr_custom_%s(self, *args, **kwargs):\n    return self._user_instrucs.%s(*args, **kwargs)\n    " % (prop, prop)
            exec(func_str)
            setattr(Instructions, prop, eval("instr_custom_%s" % prop))

    def show(self, arg):
        print(arg)

user_instructions.py如下:

class UserInstructions:

    def __init__(self, instr):
        self.__instr = instr

    def print_line(self, args):
        print(args)
相关问题