python - Python中随机选择类属性

标签 python class attributes instance

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”属性并更改它们,但我真的不知道如何调用它们。我需要这样做,以便我可以随机选择一个统计数据进行修改。我应该创建一个统计类,以便每个统计都是该类的实例吗?

任何帮助都将是巨大的。

最佳答案

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)

关于python - Python中随机选择类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10493258/

相关文章:

python - 单击 gtk.Expander 自定义标签小部件不起作用

python - Seaborn Facetgrid countplot 色调

python - 即使在实例中设置,tkinter "Class"也没有属性 "button"

ruby-on-rails - rails : Update model attribute without invoking callbacks

ios - 建模并填充核心数据与属性的多对多关系

python - 使用 Python 从 API 获取数据并使用 Azure 数据工厂加载到 Azure SQL 数据仓库中

python - 定义Python类实例属性

java - 在 java 方法中省略 public 修饰符

c# - 从 BaseClass 中的子类获取自定义属性 (C# .NET 4.0)

Python3 自定义 View 对象