Python中的动态类属性? [英] Dynamic Class Attribute in Python?
问题描述
我正在尝试为一个类编写一个函数,该函数需要一堆文件并将它们作为属性添加到该类中.
I'm trying to write a function for a class that takes a bunch of files and adds them to the class as attributes.
现在我有一个类 foo
和另一个类 bar
.我本质上想浏览一个字符串列表(这是简化的),并将每个字符串添加为 foo
的属性,并且每个属性都属于 bar 类.代码>.因此,
foo
具有一堆类型为 bar
的属性.现在,我已经使用python的 __ setattr __
做到了这一点,并且效果很好.真正的问题是,我需要在 bar
内设置一个属性,并且需要对每个单独的 foo
属性进行设置.
Right now I have some class foo
, and another class bar
. I want to essentially go through a list of strings (this is simplified), and add each of those strings as an attribute of foo
, and each of these attributes will be of class bar
. So foo
has a bunch of attributes of type bar
. Now I've done this using python's __setattr__
, and that's worked fine. The real issue is that I need to set an attribute within bar
, and I need to do this for each individual foo
attribute.
所以现在,我有一个for循环:
So for now, I have a for loop:
for name in list:
self.__setattr__(name, bar(a, b, ..))
self.name.a = 123
不幸的是,该属性被读取为名称",而不是列表中的值.因此,我收到如下错误: foo对象没有属性名称
.我需要的是某种动态访问.我知道 getattr
,但是据我所知,它返回一个值,并且我认为不适用于我的情况.你们知道在这里有用的任何东西吗?
Unfortunately, the attribute is read as "name" and not the value in the list.
So I get an error like: foo object has no attribute name
.
What I need is some kinda of dynamic access. I know of getattr
, but as far as I know, that returns a value, and I don't think is applicable in my case. Do you guys know of anything that would work here?
我也可以添加需要设置为构造函数参数的内容.我不愿意这样做的原因是,我认为它有点重载了构造函数,并使它变得混乱,特别是因为参数名称会很长.话虽如此,我可以在必要时这样做.
I can also add the things I need to set as constructor arguments too. The reason I'd prefer not to do that is I think it kind of overloads the constructor, and makes it kind of cluttered, especially since the argument names would be rather long. That being said, I can do that if necessary.
推荐答案
将bar实例保存在局部变量中:
Save the bar-instance in a local variable:
for name in list:
bar_value = bar(a, b, ..)
setattr(self, name, bar_value)
bar_value.a = 123
这篇关于Python中的动态类属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!