Set Python attributes from a list, but recall them outside of a list
-
21-12-2019 - |
Вопрос
Not sure if this the recommended way of doing things in Python. I have a class with a bunch of attributes, like so
class MyClass:
def __init__(self):
self.attr1 = "first_value"
self.attr2 = "second_value"
...
However, this is tedious, I want to be able to do this in a loop:
self.attr_list = ["attr1", "attr2", "another_attr",...]
def __init__(self, values_list):
self.attr_values = [some_func(i) for i in values_list]
But I also later want to call these values like so:
foo = MyClass(values_list)
...
bar = foo.attr1
myFunc(foo.another_attr, ..., some_other_parameters)
So the question is, how do I avoid the tedious first method where the line for each attribute is hard-coded, but still get the convenience of referring to an attribute without having to know/remember where in the list it is?
Hope this is clearer.
Thanks
P.S. I'm using Python 3
Решение
I'm not sure I understand the question. Are you looking for setattr? Something like this:
def assign(self, attr_names, value_list):
for i in range(len(attr_names)):
setattr(self, attr_names[i], some_func(value_list[i]))
You can use it like that:
foo.assign(["attr1", "attr2"], value_list)
print(foo.attr1)
I don't think that using setattr
is wrong per se however I advice using dictionaries instead since you might overwrite other attributes by accident, for example consider this:
foo.assign(["assign"], [1])
foo.assign(["assign"], [1]) # <-- exception now