0

Given an arbitrary number of people:

def __init__(self):
    self.person1 = ["Person_1", 0]
    self.person2 = ["Person_2", 0]
    ...

I would like to adjust the value "0" to "25".

How can I change the variable during each iteration so that I don't have to type it as follows:

 def daily_income(self):
    self.person1[1] += 25
    self.person2[1] += 25
    ...

I tried to adjust the variable name by appending the "i" to the end of the variable name, however, it did not work.

def daily_income(self):
    for i in range(1,3):
        'self.person_{}'.format(i)[1] += 25
3
  • appending the "i" to the end of the variable name You appended "i" to a string. Commented Oct 30, 2021 at 13:41
  • 1
    Why not use a single dictionary instead of multiple variables ? Commented Oct 30, 2021 at 18:36
  • 1
    If you just had one big self.people structure this problem wouldn't exist. Commented Oct 31, 2021 at 4:01

2 Answers 2

1

This is not a good code design, but it can be done as follows:

class People:
    def __init__(self):
        self.person1 = ["Person_1", 1]
        self.person2 = ["Person_1", 2]
        self.person3 = ["Person_1", 3]
        
    def daily_income(self):
        for i in range(1,4):
            attr = 'person{}'.format(i)
            val = getattr(self, attr)
            val[1] += 25
            setattr(self, attr, val) 
Sign up to request clarification or add additional context in comments.

Comments

0

To get the variable, either follow this:

def daily_income(self):
    for i in range(1,26):
        attr = f'person{i}'

or this: (as followed by bb1)

def daily_income(self):
    for i in range(1,26):
        attr = 'person{}'.format(i)
        val = getattr(self, attr)
        val[1] += 25
        setattr(self, attr, val) 

Comments

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.