隐式变量声明和访问 [英] implicit variable declaration and access

查看:82
本文介绍了隐式变量声明和访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何反射设施在python

我可以用来定义一个存储在另一个变量中的

名称的变量?

就像我有:

x =" myVarName"


如何使用字符串的名称声明一个新变量

存储在x中。我怎样才能在以后隐式访问?

解决方案

Ali Razavi写道:

python中是否有任何反射设施<我可以用来定义一个存储在另一个变量中的
名称的变量吗?
就像我有:
x =" myVarName"

什么我可以用x中存储的字符串名称声明一个新变量。我怎样才能在以后隐式访问?



搞定了!使用像Lisp这样的高阶函数!


code = x +''= 0''

exec(代码)


code =''print''+ x

exec(代码)


Ali Razavi写道:

Ali Razavi写道:

在python中是否有任何反射功能
我可以使用它来定义一个存储在另一个中的名称的变量变量?

搞定了!使用像Lisp这样的高阶函数!


不,你使用像Python这样的高阶函数。 :)

code = x +''= 0''
exec(代码)


一般情况下你应该远离执行原因。我不会详细说明,但搜索这个小组会提供丰富的信息。


如果你想影响全局(你可能不会) t)你可以这样做:$ block $ class =post_quotes> x =''my_var''
globals()[x] = 7
my_var
7


如果你想在特定对象上设置一个属性(可能是更多的b $ b),你可以这样做:

C类:
....传递

.... c = C()
setattr(c,x,8)
c.my_var
8

code =''print''+ x
exec(代码)




获得的值分别如下:

print globals()[x]
7 getattr(c,x)



8

HTH

-

Benji York


Benji York< be *** @ benjiyork.com>写道:


[snap]

code = x +''= 0''
exec(代码)



你应该出于很多原因远离执行官。




代码''可重构' '就是其中之一。


Is there any reflective facility in python
that I can use to define a variable with a
name stored in another variable ?
like I have :
x = "myVarName"

what can I do to declare a new variable with the name of the string
stored in x. And how can I access that implicitly later ?

解决方案

Ali Razavi wrote:

Is there any reflective facility in python
that I can use to define a variable with a
name stored in another variable ?
like I have :
x = "myVarName"

what can I do to declare a new variable with the name of the string
stored in x. And how can I access that implicitly later ?


Got it! use higher order functions like Lisp!

code = x + ''= 0''
exec(code)

code = ''print '' + x
exec(code)


Ali Razavi wrote:

Ali Razavi wrote:

Is there any reflective facility in python
that I can use to define a variable with a
name stored in another variable ?

Got it! use higher order functions like Lisp!
No, you use higher order functions like Python. :)
code = x + ''= 0''
exec(code)
You should generally stay away from exec for lots of reasons. I won''t
elaborate but a search of this group would be informative.

If you want to affect the globals (which you probably don''t) you can
do this:

x = ''my_var''
globals()[x] = 7
my_var 7

If you want to set an attribute on a particular object (which is more
likely), you can do this:
class C: .... pass
.... c = C()
setattr(c, x, 8)
c.my_var 8
code = ''print '' + x
exec(code)



Getting the value would be like this, respectively:
print globals()[x] 7 getattr(c, x)


8

HTH
--
Benji York


Benji York <be***@benjiyork.com> writes:

[snap]

code = x + ''= 0''
exec(code)



You should generally stay away from exec for lots of reasons.



Code ''refactorizability'' is one of them.


这篇关于隐式变量声明和访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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