The best way to set attributes inside a class when you need to construct their name on the fly is to use setattr
. That's exactly what it's for. And later, if you want to read the attribute values in a similar programmatic way, use getattr
.
In your code, that means:
for i in range(len(call_dates_webElements)):
temp_var = 'date_label_call_' + f"{i+1}"
temp_text = call_dates_webElements[i].text
setattr(self, temp_var, temp_text)
or just
for i in range(len(call_dates_webElements)):
setattr(self, f"date_label_call_{i+1}", call_dates_webElements[i].text)
Notes:
- I'm using
i+1
for the variable name: as @acw1668 pointed out in the comment, your loop will start at 0, but in the question you say you want your variables to start at _1
.
- I removed
self.
from temp_var
: setattr
will already add the attribute to self
, so I just need to provide the attribute name.
- You can later access these attributes as
self.date_label_call_1
if you want to hardcode the name, or with getattr(self, f"date_label_call_{i+1}") in a loop over
i`.
- That
getattr
call will raise an exception if the attribute has not been set before, but you can give it a default value to return instead when the attribute is not defined, e.g., getattr(self, f"date_label_call_{i+1}", "no such date label call found")
.