首页 > 解决方案 > 在 Python 中设置类中的属性的可索引方式

问题描述

我有一种感觉,这不是设置属性的最佳/最安全的方法,但我试图找到一种在我用 Python 编写的 CLI 程序中轻松设置属性的方法。

我有一个显示所有属性的 dunder str 输出,我将该字符串与 enumerate() 一起使用来对属性进行编号以供用户选择。然后我想出了下面的代码来访问并将新值分配给所需的属性。我知道我有一些输入验证和清理需要处理,但我想要一些关于代码片段的反馈,以了解是否有更好的方法/为什么它可能不好/改进的方法。

class TestClass:
""" test class to show effect of change attribute method """
def __init__(self):
    self.a = 1
    self.b = False
    self.c = 'string'
    self.d = 4.2
    
def setAtrib(self, index, value):
    """ from the dict keys of attributes gained from vars() creates a list for an indexable way to set attributes"""
    keys = list(vars(self).keys()) # creates list of keys
    key = keys[index] # with index gain key value
    vars(self)[key] = value # with key value set attribute to argument value

刚刚完成了我对 Python 课程的第一次介绍,但仍然习惯于 StackOverflow 的格式,所以请原谅。

感谢您的时间和精力。

编辑 - 我正在为自己创建一个时间/记录保存程序,以跟踪我作为 UPS 司机的一天。

标签: pythonpython-3.xclassattributessettings

解决方案


推荐阅读