迭代数据类键和值的更好方法是什么?

新手上路,请多包涵

我有两个数据类, RouteFactorsRoute 包含一个值和三个副本 Factors

Route 不知道有多少变量 Factors 包含。我想获取这些变量的名称,然后为 Factors 的每个副本获取每个变量的相应值。

这是我目前拥有的:

 @dataclass
class Factors:
    do: bool  # does it do the route
    hub: int # how many of the locations are hubs

    def __init__(self, do_init):
        self.do = do_init
        self.hub = 0 # will add later

    def __str__(self):
        return "%s" % self.do

@dataclass
class Route:
    route: tuple
    skyteam: Factors
    star: Factors
    oneworld: Factors

    def __init__(self, route):
        self.route = route.get('route')
        # this could probably be done with one line loop and a variable with names
        self.skyteam = Factors(route.get('skyteam'))
        self.star = Factors(route.get('star'))
        self.oneworld = Factors(route.get('oneworld'))

    def __str__(self):
        table = [[self.route, "SkyTeam", "StarAlliance", "OneWorld"]] # var name is fine
        for var in Factors.__dict__.get('__annotations__').keys():  # for each factor
            factor = [var]
            factor.append(self.skyteam.__dict__.get(var))
            factor.append(self.star.__dict__.get(var))
            factor.append(self.oneworld.__dict__.get(var))
            table.append(factor)
        return tabulate.tabulate(table, tablefmt='plain')

输入是

{'route': ('BOS', 'DXB'), 'skyteam': True, 'star': True, 'oneworld': True}

当前输出是

('BOS', 'DXB')  SkyTeam  StarAlliance  OneWorld
do              True     True          True
hub             0        0             0

也许我可以搜索 Route 包含 Factors 数据类型的每个变量并迭代这些变量?

原文由 Adin D 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 524
1 个回答

您可以使用 dataclass.fields

 from dataclasses import dataclass, fields

for field in fields(YourDataclass):
    print(field.name, getattr(YourDataclass, field.name))

原文由 Andrey Topoleov 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题