【问题标题】:How do I pull out the attributes or field names from a dataclass?如何从数据类中提取属性或字段名称?
【发布时间】:2021-08-05 14:53:49
【问题描述】:

我有一个数据类,比如Car:

from dataclasses import dataclass

@dataclass
class Car:
    make: str
    model: str
    color: hex
    owner: Owner

如何在列表中提取数据类的属性或字段?例如

attributes = ['make', 'model', 'color', 'owner']

【问题讨论】:

    标签: python python-dataclasses


    【解决方案1】:

    使用dataclasses.fields 从类或实例中提取字段。然后使用.name属性获取字段名。

    >>> from dataclasses import fields
    >>> attributes = [field.name for field in fields(Car)]
    >>> print(attributes)
    ['make', 'model', 'color', 'owner']
    

    【讨论】:

      猜你喜欢
      • 2021-11-19
      • 2011-11-05
      • 1970-01-01
      • 1970-01-01
      • 2013-04-24
      • 2021-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多