Python vars() global name error

前端 未结 5 743
一整个雨季
一整个雨季 2021-01-21 08:31

I\'m having a bit of trouble understanding what\'s going wrong with the following function:

def ness():
 pie=\'yum\'
 vars()[pie]=4
 print vars()[pie]
 print yum         


        
5条回答
  •  清歌不尽
    2021-01-21 09:14

    There is way to do it with exec

    >>> def ness():
    ...  pie='yum'
    ...  exec pie+"=4"
    ...  print vars()[pie]
    ...  print yum
    ...
    >>>
    >>> ness()
    4
    4
    

    But Instead of doing that, using a new dict is better and safe

    >>> def ness():
    ...  dic={}
    ...  pie='yum'
    ...  dic[pie]=4
    ...  print dic[pie]
    ...  print dic['yum']
    ...
    >>> ness()
    4
    4
    >>>
    

提交回复
热议问题