从字典键/值对动态设置 self.x
我有一段代码,我想将三十或四十个不断变化的键/值对转换为类下的变量。举例来说:
for i in dict:
self.i = dict[i]
但是当然,每次都会重置 self.i 。我尝试过 eval,但不能用它设置变量,因为它会将“x=1”报告为无效语法。我尝试过搜索,但我什至不太确定要搜索什么...
谢谢!
I have a slice of code where I want to transform thirty or forty ever-changing key/value pairs into variables under a class. So for instance:
for i in dict:
self.i = dict[i]
But of course that would just reset self.i each time. I've tried eval, but you cannot set variables with it, as it reports 'x=1' as invalid syntax. I've tried searching, but I'm not even quite sure what to search...
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要更新类实例,您可以使用
“我怀疑”,尽管这是解决您问题的最佳解决方案。您能否提供更多详细信息,说明为什么您认为您需要这个?
To update a class instance, you could just use
I doubt though this is the best solution for your problem. Could you provide more details why you think you need this?
这是一个方法。 Sven Marnach 是对的——你应该详细说明为什么要这样做。
Here's a way. Sven Marnach is right though -- you should say more about why you want to do this.
Python 类有一个名为 __dict__ 的内置属性。
您可以这样使用它:
在您的情况下,类似这样的东西应该有效:
Python classes have a built-in property called __dict__.
You can use it like this:
In your case, something like this should work: