Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

declaring a global dynamic variable in python

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 this:

def creatingShotInstance():

    import movieClass

    BrokenCristals = movieClass.shot()
    global BrokenCristals #here I declare BrokenCristals like a global variable and it works, I have access to this variable (that is a  shot class instance) from any part of my script.
    BrokenCristals.set_name('BrokenCristals')
    BrokenCristals.set_description('Both characters goes through a big glass
and break it')
    BrokenCristals.set_length(500)
    Fight._shots.append(BrokenCristals)

def accesingShotInstance():
    import movieClass

    return BrokenCristals.get_name()#it returns me 'BrokenCristals'

but if instead of doing that I declare a string variable like this:

def creatingShotInstance():

    import movieClass

    a = 'BrokenCristals'

    vars()[a] = movieClass.shot()
    global a #this line is the only line that is not working now, I do not have acces to BrokenCristals class instance from other method, but I do have in the same method.
    eval(a+".set_name('"+a+"')")
    eval(a+".set_description('Both characters goes through a big glass
and break it')")
    eval(a+".set_length(500)")
    Fight._shots.append(vars()[a])

def accesingShotInstance():
    import movieClass

    return BrokenCristals.get_name()#it returns me 'BrokenCristals is not defined'

I tried this :

global vars()[a]

and this:

global eval(a)

but It gives me an error. What should I do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...