问题描述
我觉得这不是设置属性的最好/最安全的方法,但是我试图找到一种方法来轻松地在我用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司机的日子。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)