有可能这样做吗?
class child:
def __init__(self):
self.figure = "Square"
self.color = "Green"
bot = child()
bot_parameters = ['color', 'figure']
[print(bot.i) for i in bot_parameters] #Attribute Error from the print function.
我知道我可以用__dict__
访问参数值,但我想知道是否可以连接参数以编程/动态地获取值。
您可以同时使用内置的vars()
和getattr()
函数,并动态检索类实例的属性,如下所示:
class Child:
def __init__(self):
self.figure = "Square"
self.color = "Green"
bot = Child()
print([getattr(bot, attrname) for attrname in vars(bot)]) # -> ['Square', 'Green']
您也可以只对['figure', 'color']
进行硬编码,但这并不是";动态的";并且每当类的属性发生更改时都必须进行更新。