是否有任何反射设施在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>写道: [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 pythonthat I can use to define a variable with aname 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> writes: [snap] code = x + ''= 0'' exec(code)You should generally stay away from exec for lots of reasons.
Code ''refactorizability'' is one of them.
更多推荐
隐式变量声明和访问
发布评论