Getting the name which is not defined from NameError in python

后端 未结 3 1118
悲哀的现实
悲哀的现实 2021-01-17 22:51

As you know, if we simply do:

>>> a > 0
Traceback (most recent call last):
  File \"\", line 1, in 
    a > 0
N         


        
3条回答
  •  遇见更好的自我
    2021-01-17 23:26

    No import exceptions needed in Python 2.x

    >>> try:
    ...     a > 0
    ... except NameError as e:
    ...     print e.message.split("'")[1]
    ...
    a
    >>>
    

    You assign the reference for 'a' as such:

    >>> try:
    ...     a > 0
    ... except NameError as e:
    ...     locals()[e.message.split("'")[1]] = 0
    ...
    >>> a
    0
    

提交回复
热议问题