如何创建可变数量的变量?

本文翻译自:How do I create a variable number of variables?

How do I accomplish variable variables in Python? 如何在Python中完成变量变量?

Here is an elaborative manual entry, for instance: Variable variables 例如,这是详尽的手动输入: 变量变量

I have heard this is a bad idea in general though, and it is a security hole in Python. 我听说这通常是个坏主意,这是Python中的一个安全漏洞。 Is that true? 真的吗?


#1楼

参考:https://stackoom.com/question/5lDo/如何创建可变数量的变量


#2楼

You can use dictionaries to accomplish this. 您可以使用字典来完成此任务。 Dictionaries are stores of keys and values. 字典是键和值的存储。

>>> dct = {'x': 1, 'y': 2, 'z': 3}
>>> dct
{'y': 2, 'x': 1, 'z': 3}
>>> dct["y"]
2

You can use variable key names to achieve the effect of variable variables without the security risk. 您可以使用变量键名来获得变量变量的效果,而不会带来安全风险。

>>> x = "spam"
>>> z = {x: "eggs"}
>>> z["spam"]
'eggs'

For cases where you're thinking of doing something like 对于您正在考虑做类似事情的情况

var1 = 'foo'
var2 = 'bar'
var3 = 'baz'
...

a list may be more appropriate than a dict. 列表可能比字典更合适。 A list represents an ordered sequence of objects, with integer indices: 一个列表代表对象的有序序列,并带有整数索引:

l = ['foo', 'bar', 'baz']
print(l[1])           # prints bar, because indices start at 0
l.append('potatoes')  # l is now ['foo', 'bar', 'baz', 'potatoes']

For ordered sequences, lists are more convenient than dicts with integer keys, because lists support iteration in index order, slicing , append , and other operations that would require awkward key management with a dict. 对于有序序列,列表比带有整数键的字典更方便,因为列表支持索引顺序的迭代, 切片append和其他需要使用字典管理笨拙键的操作。


#3楼

Whenever you want to use variable variables, it's probably better to use a dictionary. 每当您想使用变量变量时,最好使用字典。 So instead of writing 所以不要写

$foo = "bar"
$$foo = "baz"

you write 你写

mydict = {}
foo = "bar"
mydict[foo] = "baz"

This way you won't accidentally overwrite previously existing variables (which is the security aspect) and you can have different "namespaces". 这样,您就不会意外覆盖先前存在的变量(这是安全方面),并且您可以拥有不同的“命名空间”。


#4楼

Use the built-in getattr function to get an attribute on an object by name. 使用内置的getattr函数getattr名称获取对象的属性。 Modify the name as needed. 根据需要修改名称。

obj.spam = 'eggs'
name = 'spam'
getattr(obj, name)  # returns 'eggs'

#5楼

It's not a good idea. 这不是一个好主意。 If you are accessing a global variable you can use globals() . 如果要访问全局变量,则可以使用globals()

>>> a = 10
>>> globals()['a']
10

If you want to access a variable in the local scope you can use locals() , but you cannot assign values to the returned dict. 如果要在本地范围内访问变量,则可以使用locals() ,但不能将值分配给返回的dict。

A better solution is to use getattr or store your variables in a dictionary and then access them by name. 更好的解决方案是使用getattr或将变量存储在字典中,然后按名称访问它们。


#6楼

The consensus is to use a dictionary for this - see the other answers. 共识是为此使用字典-参见其他答案。 This is a good idea for most cases, however, there are many aspects arising from this: 在大多数情况下,这是一个好主意,但是,由此产生了许多方面:

  • you'll yourself be responsible for this dictionary, including garbage collection (of in-dict variables) etc. 您将自己负责此字典,包括垃圾收集(命令变量)等。
  • there's either no locality or globality for variable variables, it depends on the globality of the dictionary 变量变量既不存在局部性也不存在全局性,这取决于字典的全局性
  • if you want to rename a variable name, you'll have to do it manually 如果要重命名变量名,则必须手动进行
  • however, you are much more flexible, eg 但是,您要灵活得多,例如
    • you can decide to overwrite existing variables or ... 您可以决定覆盖现有变量或...
    • ... choose to implement const variables ...选择实现const变量
    • to raise an exception on overwriting for different types 对不同类型的覆盖提出例外
    • etc. 等等

That said, I've implemented a variable variables manager -class which provides some of the above ideas. 也就是说,我已经实现了变量变量管理器 -class,它提供了上述一些想法。 It works for python 2 and 3. 它适用于python 2和3。

You'd use the class like this: 你会使用这个类是这样的:

from variableVariablesManager import VariableVariablesManager

myVars = VariableVariablesManager()
myVars['test'] = 25
print(myVars['test'])

# define a const variable
myVars.defineConstVariable('myconst', 13)
try:
    myVars['myconst'] = 14 # <- this raises an error, since 'myconst' must not be changed
    print("not allowed")
except AttributeError as e:
    pass

# rename a variable
myVars.renameVariable('myconst', 'myconstOther')

# preserve locality
def testLocalVar():
    myVars = VariableVariablesManager()
    myVars['test'] = 13
    print("inside function myVars['test']:", myVars['test'])
testLocalVar()
print("outside function myVars['test']:", myVars['test'])

# define a global variable
myVars.defineGlobalVariable('globalVar', 12)
def testGlobalVar():
    myVars = VariableVariablesManager()
    print("inside function myVars['globalVar']:", myVars['globalVar'])
    myVars['globalVar'] = 13
    print("inside function myVars['globalVar'] (having been changed):", myVars['globalVar'])
testGlobalVar()
print("outside function myVars['globalVar']:", myVars['globalVar'])

If you wish to allow overwriting of variables with the same type only: 如果只允许覆盖相同类型的变量:

myVars = VariableVariablesManager(enforceSameTypeOnOverride = True)
myVars['test'] = 25
myVars['test'] = "Cat" # <- raises Exception (different type on overwriting)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值