如何循环遍历python类对象中的所有变量(而不将它们转换为字符串)?
假设我有一门课是这样的:如何循环遍历python类对象中的所有变量(而不将它们转换为字符串)?,python,python-3.x,Python,Python 3.x,假设我有一门课是这样的: class Colors: RED = '\33[31m' GREEN = '\33[32m' YELLOW = '\33[33m' BLUE = '\33[34m' ... 如何循环这些变量,而不将它们转换为字符串 例如: 我试图用问题的答案,但结果是: colors = [attr for attr in dir(Colors) if not callable(getattr(Colors, attr)) and not a
class Colors:
RED = '\33[31m'
GREEN = '\33[32m'
YELLOW = '\33[33m'
BLUE = '\33[34m'
...
如何循环这些变量,而不将它们转换为字符串
例如:
我试图用问题的答案,但结果是:
colors = [attr for attr in dir(Colors) if not callable(getattr(Colors, attr)) and not attr.startswith("__")]
for color in colors:
print(color + 'foo')
//prints this:
//REDfoo
//GREENfoo
...
我也试过:
colors = [attr for attr in dir(Colors) if not callable(getattr(Colors, attr)) and not attr.startswith("__")]
for color in colors:
print(Colors.color + 'foo') //error: Colors has no attribute 'color'
print(Colors[color] + 'foo') //error: Colors object is not subscriptable
有没有什么方法可以使这项工作不涉及复制/粘贴每种颜色
是我找到颜色的地方。函数返回给定对象的属性名称列表。然后应使用
getattr
函数按名称获取属性值:
colors = [getattr(Colors, attr) for attr in dir(Colors) if not callable(getattr(Colors, attr)) and not attr.startswith("__")]
或者,正如@juanpa.arrivillaga在评论中建议的那样,您可以使用vars
函数,以避免调用getattr
来获取属性值:
colors = [value for attr, value in vars(Colors).items() if not callable(value) and not attr.startswith("__")]
你为什么需要在这里上课?是否有其他您需要的功能尚未在此处共享?根据你告诉我们的,这应该只是一个简单的字典,而不是一个类。你应该使用一个枚举,然后你可以直接在这个类上迭代你真正应该使用的
vars
。dir
的意义是什么?的确如此。按建议更新。谢谢
colors = [value for attr, value in vars(Colors).items() if not callable(value) and not attr.startswith("__")]