遍历图和 return class 通过递归调用带有子节点的节点作为参数创建的实例
Traverse graph and return class instances created by recursively calling node with children for arguments
有一个图将 class 类型映射到它们的参数列表。我如何 return 用他们的祖先实例化的根作为参数? (对于我的问题可能是一个糟糕的描述表示歉意)。考虑以下因素:
graph = {Foo: [42], Baz: [None], Bar: [Baz], FooBar: [Foo, Bar], Qux: [True]}
对于由 set(graph).difference(chain.from_iterable(graph.values()))
编辑的根 return,我希望有两个值,qux
和 foobar
,创建如下:
qux = Qux(True)
foobar = FooBar(Foo(42), Bar(Baz(None)))
这里是重现示例的附加代码:
from itertools import chain
class Node:
name = None
def __init__(self, *args):
self.args = args
class FooBar(Node):
name = 'foobar'
class Foo(Node):
name = 'foo'
parent = FooBar
class Bar(Node):
name = 'bar'
parent = FooBar
class Baz(Node):
name = 'baz'
parent = Bar
class Qux(Node):
name = 'qux'
提前谢谢你。
你可以使用这个递归函数:
def get_inst (graph, arg):
val = graph[arg]
return arg(*(el if type(el) != type else get_inst (graph, el) for el in val))
此函数的示例用法:
roots = set(graph).difference(chain.from_iterable(graph.values()))
for root in roots:
val = get_inst(graph, root)
有一个图将 class 类型映射到它们的参数列表。我如何 return 用他们的祖先实例化的根作为参数? (对于我的问题可能是一个糟糕的描述表示歉意)。考虑以下因素:
graph = {Foo: [42], Baz: [None], Bar: [Baz], FooBar: [Foo, Bar], Qux: [True]}
对于由 set(graph).difference(chain.from_iterable(graph.values()))
编辑的根 return,我希望有两个值,qux
和 foobar
,创建如下:
qux = Qux(True)
foobar = FooBar(Foo(42), Bar(Baz(None)))
这里是重现示例的附加代码:
from itertools import chain
class Node:
name = None
def __init__(self, *args):
self.args = args
class FooBar(Node):
name = 'foobar'
class Foo(Node):
name = 'foo'
parent = FooBar
class Bar(Node):
name = 'bar'
parent = FooBar
class Baz(Node):
name = 'baz'
parent = Bar
class Qux(Node):
name = 'qux'
提前谢谢你。
你可以使用这个递归函数:
def get_inst (graph, arg):
val = graph[arg]
return arg(*(el if type(el) != type else get_inst (graph, el) for el in val))
此函数的示例用法:
roots = set(graph).difference(chain.from_iterable(graph.values()))
for root in roots:
val = get_inst(graph, root)