从字典键/值对动态设置 self.x

发布于 2024-12-18 02:41:42 字数 210 浏览 0 评论 0原文

我有一段代码,我想将三十或四十个不断变化的键/值对转换为类下的变量。举例来说:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一笑百媚生 2024-12-25 02:41:43

要更新类实例,您可以使用

vars(self).update(my_dict)

“我怀疑”,尽管这是解决您问题的最佳解决方案。您能否提供更多详细信息,说明为什么您认为您需要这个?

To update a class instance, you could just use

vars(self).update(my_dict)

I doubt though this is the best solution for your problem. Could you provide more details why you think you need this?

单身狗的梦 2024-12-25 02:41:43

这是一个方法。 Sven Marnach 是对的——你应该详细说明为什么要这样做。

>>> class Foo(object):
...     def __init__(self, d):
...         for k in d:
...             setattr(self, k, d[k])
... 
>>> f = Foo({'a':'b', 'c':'d'})
>>> f.a
'b'
>>> f.c
'd'

Here's a way. Sven Marnach is right though -- you should say more about why you want to do this.

>>> class Foo(object):
...     def __init__(self, d):
...         for k in d:
...             setattr(self, k, d[k])
... 
>>> f = Foo({'a':'b', 'c':'d'})
>>> f.a
'b'
>>> f.c
'd'
街道布景 2024-12-25 02:41:43

Python 类有一个名为 __dict__ 的内置属性。

您可以这样使用它:

>>> class Blah(object):
...    pass
>>> x = Blah()
>>> x.__dict__['what'] = 40
>>> x.what

在您的情况下,类似这样的东西应该有效:

self.__dict__.update(dict)

Python classes have a built-in property called __dict__.

You can use it like this:

>>> class Blah(object):
...    pass
>>> x = Blah()
>>> x.__dict__['what'] = 40
>>> x.what

In your case, something like this should work:

self.__dict__.update(dict)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文