2
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

解决这个问题的最佳方法是什么?

问题是我试图从列表中访问这些“统计”属性并更改它们,但我真的不知道如何调用它们。我需要这样做,以便我可以随机选择要修改的统计数据。我应该创建一个统计类,以便每个统计都是该类的一个实例吗?

任何帮助都会很棒。

4

2 回答 2

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
于 2012-05-08T06:00:51.100 回答
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)
于 2012-05-08T05:57:09.870 回答