0

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.

2
  • Do you mean getattr(self, name).a = 123? It's not really clear why you can't pass 123 into the class, you may have larger structural problems. Also you should use setattr rather than calling __setattr__. Commented Jun 11, 2015 at 20:44
  • Yes you're right, I was over thinking things and was stuck with the concept of self.name.attribute for some reason. Commented Jun 11, 2015 at 20:54

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Ah yes. I tried something similar, but made in a way dumber way. I completely overlooked this in my effort to over complicate things for myself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.