假设我有一个 python 程序,它是一个黑匣子,其作用就像一个处理器。它读取带有一些指令名称的文本文件,解析该文件并调用指令类中的函数。我想要的是允许用户在另一个文件中创建新函数,并允许处理器通过Instructions类调用这些函数。
示例处理器代码(无法更改):
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')
我想以某种方式将用户函数合并到类 Instructions 中,以便处理器能够运行以下“program.txt”:
print_line 'Hello'
简而言之,我想将指令函数分为两个文件,一个文件包含一些基本的“固定”指令,另一个文件包含用户定义的“动态”函数。最后我想在类Instructions中加载这两个函数。
最佳答案
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)
关于python - 将自定义函数添加到 Python 中的现有类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51959029/