简体   繁体   English

访问Anytree节点中的** kwargs

[英]accessing **kwargs in anytree nodes

I'm new to Python/AnyTree and am trying to get a list of raw ingredients to make a bunch of Harburgers (Hamburgers at Point San Pablo Harbor near San Francisco - you need to check it out if you're in the area!! In fact, the winning answer here gets a free Harburger on me next time you're in town!) But I digress... 我是Python / AnyTree的新手,正在尝试获取制作汉堡包的原料清单(汉堡附近的Point San Pablo Harbor的汉堡包-如果您在该地区,则需要检查一下!!实际上,下次您到城里时,这里的成功答案将免费为我提供汉堡包!)但是我离题了……

The question is how can I get access to the 'qty' and 'uom' fields in the tree? 问题是如何获取树中的“ qty”和“ uom”字段?

from anytree import Node, RenderTree, PreOrderIter
Harburger=Node("Harburger", children=[
        Node("RoundRoll", qty=1, uom='ea'),
        Node("GriddleGhee", qty = 1, uom='gm'),
        Node("SmashedBurger", qty = 5, uom='oz')])

print(RenderTree(Harburger))

Node('/Harburger')
├── Node('/Harburger/RoundRoll', qty=1, uom='ea')
├── Node('/Harburger/GriddleGhee', qty=1, uom='gm')
└── Node('/Harburger/SmashedBurger', qty=5, uom='oz')

So far, so good. 到现在为止还挺好。 Now I can traverse the tree, like: 现在,我可以遍历树,例如:

#print ingredients for 5 Harburgers
print([(node.name for node in PreOrderIter(Harburger)])

['Harburger', 'RoundRoll', 'GriddleGhee', 'SmashedBurger']

How can I modify this command to get qty and uom? 如何修改此命令以获取数量和uom?

I've tried 我试过了

print([(node.name, node.qty) for node in PreOrderIter(Harburger)])

only to get errors! 只得到错误!

The issue your code accessing the extra attributes has is that the top-level Node doesn't have the qty and uom attributes, so when it comes up first in the pre-order tree traversal, the code quits with an exception. 您访问额外属性的代码存在的问题是,顶级Node没有qtyuom属性,因此当它在预排序树遍历中首先出现时,代码会异常退出。

You can fix this in a few ways. 您可以通过几种方式解决此问题。 One way, which you've commented has worked, is to add the attributes to the root node too. 您评论过的一种方法是,也将属性添加到根节点。

Another option might be to test for the attributes before using them, with something like: 另一种选择可能是在使用属性之前测试它们,例如:

print([(node.name, node.qty) for node in PreOrderIter(Harburger) if hasattr(node, "qty")])

If you can rely upon your tree only having the two levels (the top-level root node and its children), you can iterate over just the child nodes instead of doing a full traversal. 如果您仅依赖具有两个级别的树(顶级根节点及其子级),则可以仅遍历子级节点,而不必进行完整遍历。 Just use Harburger.children rather than PreOrderIter(Harburger) . 只需使用Harburger.children而不是PreOrderIter(Harburger)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM