从字符串命名对象 [英] naming objects from string
问题描述
如果我有一个字符串,我如何将该字符串名称赋予python对象,
如元组。
例如
a =''你好''
b =(1234)
然后是一个函数
name(b)= a
这意味着:
hello =(1234)
这可能吗?
Hi,
If I have a string, how can I give that string name to a python object,
such as a tuple.
e.g.
a = ''hello''
b=(1234)
and then a function
name(b) = a
which would mean:
hello=(1234)
is this possible?
推荐答案
manstey写道:
manstey wrote:
如果我有一个字符串,我该如何将该字符串名称赋予python对象,
比如一个元组。
例如
a =''你好''
b =(1234)
然后是一个函数
name(b)= a
这意味着:
hello =(1234)
这可能吗?
Hi,
If I have a string, how can I give that string name to a python object,
such as a tuple.
e.g.
a = ''hello''
b=(1234)
and then a function
name(b) = a
which would mean:
hello=(1234)
is this possible?
取决于您的命名空间,但对于本地命名空间,你可以用这个:
pya = object()
py a
<对象物在0x40077478>
pylocals()[''bob''] = a
pybob
<对象在0x40077478>
类似的方法可用于全局命名空间。
James
-
James Stroud
加州大学洛杉矶分校基因组学和蛋白质组学研究所
Box 951570
洛杉矶,CA 90095
http:// www。 jamesstroud.com/
但如果我这样做,这不起作用:
a = object()
x =''bob''
locals()[x] = a
我该怎么做?
James Stroud写道:
Hi,
But this doesn''t work if I do:
a=object()
x=''bob''
locals()[x] = a
How can I do this?
James Stroud wrote:
manstey写道:
manstey wrote:
如果我有一个字符串,我该如何将该字符串名称赋予python对象,
比如一个元组。
例如
a =''你好''
b =(1234)
然后是一个函数
name(b)= a
这意味着:
hello =(1234)
这可能吗?
Hi,
If I have a string, how can I give that string name to a python object,
such as a tuple.
e.g.
a = ''hello''
b=(1234)
and then a function
name(b) = a
which would mean:
hello=(1234)
is this possible?
取决于您的命名空间,但对于本地命名空间,您可以使用:
pya = object()
pya
<对象物位于0x40077478>
pylocals()[''bob''] = a
pybob
<对象在0x40077478>
类似的方法可以用于全局命名空间。
James
-
James Stroud
加州大学洛杉矶分校基因组学和蛋白质组学研究所
方框951570
洛杉矶,加利福尼亚州90095
http://www.jamesstroud.com/
manstey写道:
manstey wrote:
如果我有一个字符串,如何将该字符串名称赋予python对象,
如元组。
例如
>
a =''你好''
b =(1234)
然后是一个函数
名称(b)= a
这意味着:
hello =(1234)
这可能吗?
If I have a string, how can I give that string name to a python object,
such as a tuple.
e.g.
a = ''hello''
b=(1234)
and then a function
name(b) = a
which would mean:
hello=(1234)
is this possible?
直接答案:
查找setattr()函数(DO查找它!)。替换你的
名称(b)=一行
setattr(__ builtins __,a,b)。
你去。
希望更有帮助的答案:
一种替代方法是使用字典。那么你的例子就是
翻译成:
a =''你好''
b =(1234,)#注意逗号!
#没有它,它不是一个元组而是一个简单的
#括号整数
d = {}#your dictionary
d [a] = b#将b的值赋给一个由一个键给出的键
d [a]
Direct answer:
Look up the setattr() functions (DO look it up!). Replace your
name(b) = a line with
setattr(__builtins__, a, b).
There you go.
Hopefully more helpful answer:
One alternative would be using a dictionary. Your example would then
translate to:
a = ''hello''
b = (1234,) # notice the comma!
# without it, it wouldn''t be a tuple but a simple
# parenthesized integer
d = {} # your dictionary
d[a] = b # assign the value of b to a key given by a
d[a]
>>(1234,)
>>(1234,)
d [''hello'']
d[''hello'']
>> (1234,)
>>(1234,)
在大多数情况下,与搞乱
相比,这将更加麻烦模块属性。
希望有所帮助
wildemar
In most cases this will be a LOT less cumbersome compared to messing
with module attributes.
hope that helps a bit
wildemar
这篇关于从字符串命名对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!