Jpwang
Jpwang

Reputation: 143

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.

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.

So for now, I have a for loop:

for name in list:
  self.__setattr__(name, bar(a, b, ..))
  self.name.a = 123

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?

EDIT: 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.

Upvotes: 0

Views: 2685

Answers (1)

Daniel
Daniel

Reputation: 42778

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

Upvotes: 3

Related Questions