python - 在 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 司机的一天。
解决方案
推荐阅读
- javascript - 按日期排序,空值无效 JSON 对象。
- json - 如何读取无效的 JSON 格式亚马逊 firehose
- python - 无法使用 pydobc 在 AWS Lambda 中使用 Python 3.6 中的 pyodbc 连接到 SQL Server
- javascript - 有没有办法访问在 Vue js 中该元素的元素上声明的数据?
- java - Javax UriBuilder 错误
- html - 谷歌浏览器不会调整视频横幅的大小
- python - 找不到我得到的 AttributeError 的来源
- angular - 在 Angular 单元测试中访问元素的内联样式
- vba - VBA - 仅在使用自定义对象的属性时出现溢出错误
- amazon-web-services - 不同 EC2 实例之间的入口和出口规则的使用