declaring a global dynamic variable in python

后端 未结 3 1187
滥情空心
滥情空心 2020-12-11 04:40

I\'m a python/programming newbie and maybe my question has no sense at all.

My problem is that I can\'t get a variable to be global if it is dynamic, I mean I can do

相关标签:
3条回答
  • 2020-12-11 05:28

    Instead of a dynamic global variable, use a dict:

    movies = {}
    
    a = 'BrokenCristals'
    
    movies[a] = movieClass.shot()
    movies[a].set_name(a)
    # etc
    
    0 讨论(0)
  • 2020-12-11 05:43

    For completeness, here's the answer to your original question. But it's almost certainly not what you meant to do -- there are very few cases where modifying the scope's dict is the right thing to do.

    globals()[a] = 'whatever'
    
    0 讨论(0)
  • 2020-12-11 05:43

    The global keyword specifies that a variable you're using in one scope actually belongs to the outer scope. Since you do not have nested scopes in your example, global doesn't know what you're trying to do. See Using global variables in a function other than the one that created them

    0 讨论(0)
提交回复
热议问题