【问题标题】:Why this code is not able call function inside another function in python为什么这段代码不能在 python 的另一个函数中调用函数
【发布时间】:2017-12-28 08:26:38
【问题描述】:

我正在尝试在 Python 中实现单链表。这是我的 _Node 类:

#!/usr/bin/env python3
class _Node:
    """Node class to create new nodes"""
    def __init__(self, data=None, next=None):
        """Construction of node"""
        self._data = data
        self._next = next

我已经从这个代码示例中删除了 push()、pop() 和其他方法。他们都在工作。

class LinkedList:
      """Singly Linked List implementation for storage"""
    def __init__(self):
        """Construction of Linked List"""
        self._head = None
        self._size = 0

    def __len__(self):
        """Return length of linked list."""
        self._count = 0
        self._current = self._head
        while self._current:
            self._count += 1
            self._current = self._current._next
        return self._count

    def value_at(self, index):
        """Return Value at given index"""
        self._current = self._head
        self._index = index
        count = ans = 0
        while count<= self._index:
            if self._current == None:
               return "List is empty."
            ans = self._current._data
            self._current = self._current._next
            count += 1
        return ans

    def value_n_from_end(self, n):
        """Get value of nth element starting from end"""
        self.n=n
        self.n = int(self.__len__() - self.n -1)
        print(self.n) #print value as expected
        self.value_at(self.n)

现在我的问题是我可以从value_at() 获得价值,但无法从课堂外的value_n_from_end() 获得价值。 输入:-

l = LinkedList()
print(l)
print(l.__len__())
print(l.value_at(1))
print(l.value_n_from_end(2))

输出:-

5-> 3-> 4-> 6->  //My Linked List
4                //Length of linked list
3                //Value return by l.value_at(1)
1                //This is the value which i want to pass in self.value_at(self.n)
None             //This is returned from (l.value_n_from_end(2))

l.value_n_from_end(2) 的值应与l.value_at(1) 相同,即 3。但我缺少一些东西。

【问题讨论】:

  • value_n_from_end 不返回任何内容。
  • value_n_from_end 中没有 return 语句。另外,由于这是一个单链表,我不确定您是否需要该方法。
  • 但是value_n_from_end调用value_atvalue_at返回值。
  • 你仍然需要从这个方法中返回它。所以你必须添加return self.value_at(self.n)
  • 哦,我明白了。我在想value_at 会返回这个值。谢谢

标签: python python-3.x function class linked-list


【解决方案1】:

value_n_from_end 不返回任何内容。你应该写:

return self.value_at(self.n)

确实,self.value_at(self.n) 在函数value_n_from_end 中返回您想要的内容,但是您必须使用 return 语句将其返回给您。否则绑定到函数命名空间。

【讨论】:

    猜你喜欢
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 2015-07-10
    • 1970-01-01
    相关资源
    最近更新 更多