python在if语句中引发异常

2024-07-02 12:14:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我想测试对象名中是否有特定的字符串,并根据它返回路径名。如果找不到任何东西,我想抛出一个错误。 这是我的密码:

def object_path(object_name):
    try:
        if object_type(object_name) in ['JX', 'JW', 'MT', 'WF']:
            obj_path = 'task'
        elif object_type(object_name) in ['TT', 'MT', 'FT']:
            obj_path = 'trigger'
        elif object_type(object_name) == 'VR':
            obj_path = 'virtual'
        else:
            raise ValueError()
    except ValueError as err:
        print('The name of  object {} is 
           incorrect'.format(object_name))
    return obj_path

if __name__ == "__main__":

    x = object_path('L8H_gh_hgkjjkh')
    print (x)

似乎不对,这就是它让我回想起的:

The name of UAC object L8H_gh_hgkjjkh is incorrect
Traceback (most recent call last):
  File "uac_api_lib.py", line 29, in <module>
    x = object_path('L8H_gh_hgkjjkh')
  File "uac_api_lib.py", line 24, in object_path
    return obj_path
UnboundLocalError: local variable 'obj_path' referenced before assignment

你能帮我修一下吗


Tags: thepathnameinobjifobjecttype
2条回答

“分配前引用”错误是因为对象路径只存在于try/except块中。在那之前先定义一下

def object_path(object_name):
    obj_path = ""
    try:
        if object_type(object_name) in ['JX', 'JW', 'MT', 'WF']:
            obj_path = 'task'
        elif object_type(object_name) in ['TT', 'MT', 'FT']:
            obj_path = 'trigger'
        elif object_type(object_name) == 'VR':
            obj_path = 'virtual'
        else:
            raise ValueError()
    except ValueError as err:
        print('The name of  object {} is 
           incorrect'.format(object_name))
    return obj_path

如果希望函数抛出ValueError,那么不要在函数中捕捉它

def object_path(object_name):
    if object_type(object_name) in ['JX', 'JW', 'MT', 'WF']:
        obj_path = 'task'
    elif object_type(object_name) in ['TT', 'MT', 'FT']:
        obj_path = 'trigger'
    elif object_type(object_name) == 'VR':
        obj_path = 'virtual'
    else:
        raise ValueError('The name of object {} is incorrect'.format(object_name))
    return obj_path

此外,您可以将其简化为:

def object_path(object_name):
    otype = object_type(object_name)
    if otype in {'JX', 'JW', 'MT', 'WF'}:
        return 'task'
    if otype in {'TT', 'MT', 'FT'}:
        return 'trigger'
    if otype == 'VR':
        return 'virtual'
    raise ValueError('The name of object {} is incorrect'.format(object_name))

但这取决于你

相关问题 更多 >