class person():
def __init__(self):
self.height = 3.0
self.weight = 240.0
self.temp = 99.23
self.statlist = [self.height, self.weight, self.temp]
def grow(self):
self.statlist[1] = self.statlist[1] + 26.0
最好的方法是什么?
问题是我试图从列表中访问这些'stat'属性并改变它们,但我真的不知道如何调用它们。我需要这样做,所以我可以随机选择要修改的统计数据。我应该创建一个统计类,以便每个stat都是该类的实例吗?
任何帮助都会很棒。
答案 0 :(得分:1)
使用getattr()和setattr():
import random
class person():
def __init__(self):
self.height = 3.0
self.weight = 240.0
self.temp = 99.23
self.statlist = ["height", "weight", "temp"]
def grow(self):
name = random.choice(self.statlist)
setattr(self, name, getattr(self, name) + 26.0)
def __str__(self):
return "%f, %f, %f" % (self.height, self.weight, self.temp)
p = person()
print p
p.grow()
print p
p.grow()
print p
输出是:
3.000000, 240.000000, 99.230000
3.000000, 266.000000, 99.230000
3.000000, 266.000000, 125.230000
答案 1 :(得分:0)
import random
class person():
def __init__(self):
self.height = 3.0
self.weight = 240.0
self.temp = 99.23
self.attrlist = ['height', 'weight', 'temp']
def grow(self):
rand_attr = random.choice(self.attrlist)
attr_value = getattr(self, rand_attr)
setattr(self, rand_attr, attr_value + 26.0)