从类中创建全局变量(从字符串) [英] Creating a global variable (from a string) from within a class

查看:76
本文介绍了从类中创建全局变量(从字符串)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上下文:我正在制作 Ren'py 游戏.值为 Character().是的,我知道在这种情况下这是一个愚蠢的想法.

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

我尝试过 vars()[]globals()[variable] = value 等,但它们根本不起作用(它们甚至没有定义任何)这是我的问题.

I have tried vars()[], globals()[variable] = value, etc, and they simply do not work (they don't even define anything) 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.

如何在类中创建全局范围内的变量,使用字符串作为变量名,而不使用 python 中的属性或 exec?

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.

推荐答案

首先:我们在 Python 中所说的全局"作用域实际上是模块"作用域(从好的方面来说,它减少了使用全局变量的弊端").

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)

即使在您的测试示例中,您也创建了向方法传递字符串的abc"变量,但随后您必须使用硬编码的abc"来访问它 - 语言本身旨在阻止这种情况(因此与Javascript,其中数组索引和对象属性是可以互换的,而在 Python 中你有不同的 Mapping 对象)

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

(附带说明,在 Pyhton 2 中总是从对象"继承类)

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

这篇关于从类中创建全局变量(从字符串)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆