1

I want to set x from variables in self.x. For example

for i in range(72)
    self.("entry" + "%s" %(i)) = None

Briefly i want to set all entry1, entry2, ... ,entry72 to None like this in short way.

self.entry1 = None
self.entry2 = None
self.entry3 = None
self.entry4 = None
.
.
self.entry72 = None

in short way. But i take

        print self.("entry" + "%s" %(i))
               ^
SyntaxError: invalid syntax

How to set self.attibutes from variables?

2
  • 1
    consider instead having a single list, self.entries, as an attribute. Commented May 13, 2014 at 16:25
  • 2
    yeah, i can't think of a possible case when it's ever a good idea to have that many numbered variables. Commented May 13, 2014 at 16:28

1 Answer 1

3

Use built-in setattr function to set dynamically named attributes:

for i in range(72):
    setattr(self, 'entry{0}'.format(x), None)

As others have pointed out in comments, there are probably no use-cases for 72 attributes named like that. While this will work, consider using different data type, e.g. dictionary:

self.entries = {}
for i in range(72):
    self.entries[i] = None
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.