隐式变量声明和访问

编程入门 行业动态 更新时间:2024-10-25 20:22:40
本文介绍了隐式变量声明和访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否有任何反射设施在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.

更多推荐

隐式变量声明和访问

本文发布于:2023-11-10 22:50:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1576679.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   声明   隐式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!