Код: Выделить всё
class TreeNode:
def __init__(self, data):
self.data=data
self.children=[]
self.parent=None
def add_child(self, child):
child.parent=self
self.children.append(child)
Теперь у меня есть функция, которая генерирует дерево, например:
Код: Выделить всё
def build_product_tree():
laptop=TreeNode("Laptop")
laptop.add_child(TreeNode("Mac"))
laptop.add_child(TreeNode("Surface"))
laptop.add_child(TreeNode("Thinkpad"))
root=TreeNode("Electronics")
root.add_child(laptop)
return root
Код: Выделить всё
def build_product_tree():
command='laptop=TreeNode('Laptop')'
exec(command)
command='laptop.add_child(TreeNode('Mac'))'
exec(command)
command='laptop.add_child(TreeNode('Surface'))'
exec(command)
command='laptop.add_child(TreeNode('Thinkpad'))'
exec(command)
command='root=TreeNode('Electronics')'
exec(command)
command='root.add_child(laptop)'
exec(command)
return root
Я пытался разделить строки и использовать eval, getattr... без устранения проблемы.
Подробнее здесь: https://stackoverflow.com/questions/791 ... th-exec-ev