如何动态调用class实例属性?

How to dynamic call class instance attribute?

我正在使用 hl7apy parse 做一些解析工作,我遇到了一个问题。
我使用hl7apy解析hl7消息,可以解析为:

from hl7apy.parser import parse_message
message = "MSH|^~\&|HIS|HIS|MediII|MediII|20170902141711||ORM^O01^ORM_O01|15b 37e7132504a0b95ade4654b596dc5|P|2.4\r"
msg = parse_message(message, find_groups=False)
print(msg.msh.msh_3.msh_3_1.value)

输出:

'HIS'

那么,如何根据field config动态获取field值?
例如,msh 字段配置:

{
    "field": "msh",
    "field_index": [3,1]
}

因此可以通过以下方式找到该值:

msg.msh.msh_3.msh_3_1.value

如果配置更改为:

{
    "field": "pid",
    "field_index": [2,4]
}

获取字段行将是:

msg.pid.pid_2.pid_2_4.value

您可以组合一些 list 理解并递归地使用 getattr

# recursively get the methods from a list of names
def get_method(method, names):
    if names:
        return get_method(getattr(method, names[0]), names[1:])
    return method

field_config = {
    'field': 'msh',
    'field_index': [3, 1]
}
# just get the field
field = field_config['field']
# get a list of the indexes as string. ['3', '1']
indexes = [str(i) for i in field_config['field_index']]
# join the indexes with a '_' starting with nothing
# and put it in a list of names. ['msh', 'msh_3', 'msh_3_1']
names = ['_'.join([field] + indexes[:i]) for i in range(len(indexes) + 1)]
# get the method from the recursive function
method = get_method(msg, names)
print(method.value)

作为免责声明,我无法对其进行测试,因此它可能无法完全按照您的预期工作。但这应该是一个很好的起点。