[英]How can I dynamically add local variables to dynamically created Python class methods
I'm creating instrument classes for use with pyvisa. 我正在创建与pyvisa一起使用的乐器类。 Rather than manually convert every SCPI command (about 400) into methods, I'd like to just copy the command quick reference into a text file and have commands like this:
我不想手动将每个SCPI命令(大约400个)转换为方法,而是将命令快速引用复制到文本文件中,并执行如下命令:
[SENSe:]TEMPerature:TRANsducer:RTD:RESistance[:REFerence]? [{MIN|MAX}]
Wind up as methods like this: 像这样的方法结束:
def temp_tran_rtd_res_qry(*args):
<check for valid arguments>
cmd = 'TEMPerature:TRANsducer:RTD:RESistance?'
argstr = ''
for arg in args:
argstr += ' ' + arg
return self.query(cmd + argstr)
I have a handle on parsing the commands, and I figured out how to use setattr()
to create the methods with the correct names from a template function. 我有一个解析命令的句柄,我想出了如何使用
setattr()
从模板函数创建具有正确名称的方法。
The part that's giving me trouble is where each method knows what to assign to cmd
. 给我带来麻烦的部分是每个方法都知道要分配给
cmd
。 I thought I might add the original strings to the class as attributes (named similar to the methods) and parse them on the fly in the methods, but for this, the methods to be able to retrieve class attributes based on their names (or something). 我以为我可以将原始字符串作为属性(命名类似于方法)添加到类中,并在方法中动态解析它们,但为此,能够根据名称(或者某些东西)检索类属性的方法)。
So, here's what I figured out: 所以,这就是我想到的:
>>> class A(object):
pass
>>> a = A()
>>> a. # Only default 'object' methods avaliable
>>> cmdstr = '[SENSe:]VOLTage[:DC]:RANGe[:UPPer] {<range>|MIN|MAX|DEF} '
>>> querystr = """def query(cls, *args): cmd = '{s}'; return command_handler(*args, cmdstr=cmd)"""
>>> exec(querystr.format(s=cmdstr))
>>> setattr(A, command_name(command_abridge(cmdstr)), classmethod(query))
>>> a.volt_rang() # Autocomplete works
<results from command_handler()>
I can write a file parser into __init__
to add a method to the class for each command string in a text file and I can write a generic method to parse the arguments and build the command strings for the actual queries. 我可以将文件解析器写入
__init__
,为文本文件中的每个命令字符串添加一个方法,我可以编写一个泛型方法来解析参数并为实际查询构建命令字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.