【问题标题】:Programmatically Create Dictionary from Class [duplicate]以编程方式从类创建字典 [重复]
【发布时间】:2021-07-15 16:23:04
【问题描述】:

使用 Python3,如果我有一个名为 COLOR 的类

class COLOR:
    RED =   '\x1b[41m'
    GREEN = '\x1b[42m'
    BLUE =  '\x1b[44m'

我可以这样创建字典

myColor = {
    "RED":   COLOR.RED,
    "GREEN": COLOR.GREEN,
    "BLUE":  COLOR.BLUE,
}

是否有一种 Python 方式以编程方式循环遍历类中的所有元素并自动创建字典?

【问题讨论】:

  • 这有什么意义?您可以使用 COLOR.getattr("RED") 而不是 myColor["RED"]
  • 您可能还想查看enum 类。

标签: python python-3.x class dictionary


【解决方案1】:

试试内置函数dir()

>>> dir(COLOR)
['BLUE', 'GREEN', 'RED', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']

使用字典理解:

mydict = {name: getattr(COLOR, name)
    for name in dir(COLOR)
    if not name.startswith("__")}

检查结果:

>>> mydict
{'BLUE': '\x1b[44m', 'GREEN': '\x1b[42m', 'RED': '\x1b[41m'}

【讨论】:

    猜你喜欢
    • 2019-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-11
    • 2011-09-05
    • 1970-01-01
    相关资源
    最近更新 更多