0

Is there a way to increment attribute of multiple class instances? Say I have a dictionary that contains how much money each person has:

money = {'John':20, 'Mary':5, 'Robert':10}

I can increment the values for all three person by doing:

for person, value in money.items():
    money[person] += 10

This gives:

{'Mary': 15, 'John': 30, 'Robert': 20}

What about classes?

class person:
    def __init__(self, name, money):
        self.name = name
        self.money = money

Mary = person("Mary",5)
Robert = person("Robert",10)
John = person("John",20)

What do I need to do to increment the money value of all the class instances?

Result should be:

Mary.money == 15
Robert.money == 20
John.money == 30

3 Answers 3

2
people = (Mary, Robert, John)

for person in people:
    person.money += 10

EDIT: Also name your class properly (Person)! Check out python's conventions.

Sign up to request clarification or add additional context in comments.

Comments

0

You should probably put all the instances in one list and use a for.

for person in people:
    person.money += 10

It's also possible to get every instance of the class person and increment each .money for all of them, but it's not very "safe" (e.g. you can have some instances of this class that you don't want to change) and "pythonic". If you still want to do it, you can do it like this:

import gc

for obj in gc.get_objects():
    if isinstance(obj, person):
        obj.money += 1

Comments

-1

You can make the class support saving any instance that is created, and then use it:

class Person:
    people = [] # <-- creates a list 
    def __init__(self, name, money):
        self.name = name
        self.money = money
        person.people.append(self) # <-- save the instance into the list

    def __repr__(self):
        return self.name + ' ' + str(self.money) # for printing purpose



Mary = Person("Mary",5)
Robert = Person("Robert",10)
John = Person("John",20)

for p in Person.people:
    p.money += 10
    print p

OUTPUT

Mary 15
Robert 20
John 30

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.