Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Creating a global variable (from a string) from within a class

Context: I'm making a Ren'py game. The value is Character(). Yes, I know this is a dumb idea outside of this context.

I need to create a variable from an input string inside of a class that exists outside of the class' scope:

class Test:
    def __init__(self):
        self.dict = {} # used elsewhere to give the inputs for the function below.

    def create_global_var(self, variable, value):
        # the equivalent of exec("global {0}; {0} = {1}".format(str(variable), str(value)))
        # other functions in the class that require this.

Test().create_global_var("abc", "123") # hence abc = 123

I have tried vars()[], globals()[variable] = value, etc, and they simply do not work (they don't even define anything) Edit: this was my problem.

I know that the following would work equally as well, but I want the variables in the correct scope:

setattr(self.__class__, variable, value) # d.abc = 123, now. but incorrect scope.

How can I create a variable in the global scope from within a class, using a string as the variable name, without using attributes or exec in python?

And yes, i'll be sanity checking.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

First things first: what we call "global" scope in Python is actually "module" scope (on the good side, it diminishes the "evils" of using global vars).

Then, for creating a global var dynamically, although I still can't see why that would be better than using a module level dictionary, just do:

globals()[variable] = value

This creates a variable in the current module. If you need to create a module variable on the module from which the method was called, you can peek the globals dictionary from the caller frame using:

from inspect import currentframe
currentframe(1).f_globals[variable] = name

Now, the this seems specially useless since you may create a variable with a dynamic name, but you can't access it dynamically (unless using the globals dictionary again)

Even in your test example, you create the "abc" variable passing the method a string, but then you have to access it by using a hardcoded "abc" - the language itself is designed to discourage this (hence the difference to Javascript, where array indexes and object attributes are the interchangeable, while in Python you have distinc Mapping objects)

My suggestion is that you use a module level explicit dictionary and create all your dynamic variables as key/value pairs there:

names = {}
class Test(object):
    def __init__(self):
        self.dict = {} # used elsewhere to give the inputs for the function below.

    def create_global_var(self, variable, value):
         names[variable] = value

(on a side note, in Pyhton 2 always inherit your classes from "object")


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...