【问题标题】:Passing a function through a linked list of objects通过对象的链表传递函数
【发布时间】:2017-02-09 18:55:02
【问题描述】:

我有一个创建多重链表的类。每个节点可以有几个(或一个或没有)子节点。该节点有一个指向其最新子节点的指针,每个子节点都有一个指向其前一个兄弟节点的指针。所以我可以依次带走每个最新的孩子,然后是它的每个兄弟姐妹,从而遍历整棵树。这个函数成功地遍历了三个,但没有做任何有用的事情:

def walk_the_tree(self):
    if not self.latestChild is None:
        self.latestChild.walk_the_tree()
    if not self.sib is None:
        self.sib.walk_the_tree()

现在,我真正想做的是传递某种参数,以便可以在每个节点上执行成员函数。这是一些无法编译的东西,但我希望它能得到我想要的:

def walk_the_tree(self, fcn):
    self.fcn()
    if not self.latestChild is None:
        self.latestChild.walk_the_tree()
    if not self.sib is None:
        self.sib.walk_the_tree()

因此,例如,fcn 可能只是 __repr__ 类,因此我可以快速获取所有节点的所有信息。或者它可能是create_new_child(),它将确定节点是否需要新的子节点,如果需要,则创建它。我希望用户能够在不依赖某种标志的情况下选择它。例如,我不想要是这样的:

def walk_the_tree(self, fcnflg):
    if (fcnflg == 1): self.__repr__()
    if (fcnflg == 2): self.create_new_child()
    if not self.latestChild is None:
        self.latestChild.walk_the_tree()
    if not self.sib is None:
        self.sib.walk_the_tree()

有什么办法吗?

【问题讨论】:

  • 函数是一流的对象。所以它应该可以工作。不要这样做self.fnc,因为它不会被定义。
  • 这绝对是一种 OOP 实践,但 obj.walk_the_tree(obj.create_new_child) 正是您要找的东西
  • 是的,我只是将其设为模块级函数。 def walk_tree(tree, f)。不过,我对保持课程简洁非常激进,这绝对是一种方法。
  • @juanpa.arrivillaga 非常感谢一个例子,如果它不是太麻烦的话。谢谢。
  • @bob.sacamento 我添加了一个使用方法的示例。该类只是包装了一个列表,但它应该能够理解这一点。

标签: python function object linked-list


【解决方案1】:

问题是您使用的是self.fcn,但未定义。只需使用fcn。这是一个人为的例子:

>>> class MyContainer(object):
...     def __init__(self, iterable=None):
...         if iterable is not None:
...             self.data = list(iterable)
...         else:
...             self.data = []
...     def walk_container(self, f):
...         for x in self.data:
...             print(f(x))
...     def _increment(self, x):
...         return x + 1
...     def print_increments(self):
...         self.walk_container(self._increment)
...
>>> c = MyContainer([0,1,2])
>>> c.print_increments()
1
2
3
>>>

或者,如果您愿意,可以在外部使用非方法:

>>> c.walk_container(lambda x: x**2)
0
1
4
>>>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多