有没有办法增加多个类实例的属性? 假设我有一本字典,其中包含每个人有多少钱:
money = {'John':20, 'Mary':5, 'Robert':10}
我可以通过执行以下操作来增加所有三个人的值:
for person, value in money.items():
money[person] += 10
这给出:
{'Mary': 15, 'John': 30, 'Robert': 20}
类(class)怎么样?
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)
我需要做什么来增加所有类实例的货币值(value)?
结果应该是:
Mary.money == 15
Robert.money == 20
John.money == 30
最佳答案
people = (Mary, Robert, John)
for person in people:
person.money += 10
编辑:还要正确命名您的类(class)(Person
)!查看python's conventions .
关于python - 增加多个类实例的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32707261/