【问题标题】:Python: calling inner() from outer()Python:从外部()调用内部()
【发布时间】:2026-01-08 17:25:06
【问题描述】:

我环顾四周,令人惊讶的是没有找到这个问题的答案。我认为这是因为通常内部/嵌套函数用于特定的东西(例如维护环境变量,工厂),而不是像我试图使用它们那样微不足道的东西。无论如何,我似乎找不到任何关于如何从外部函数正确调用内部函数的信息,而不必在文件中声明 inner() 以上outer()。问题出在 HackerRank (https://www.hackerrank.com/challenges/circular-array-rotation/problem) 上的这个问题。

def circularArrayRotation(a, k, queries):

    def rotateArrayRightCircular(arr: list, iterations: int) -> list:
        """
        Perform a 'right circular rotation' on an array for number of iterations.
        Note: function actually moves last 'iterations' elements of array to front of array.

        >>>rotateArrayRightCircular([0,1,2], 1)
        [2,0,1]

        >>>rotateArrayRightCircular([0,1,2,3,4,5], 3)
        [3,4,5,0,1,2]

        >>>rotateArrayRightCircular([0,1,2,3,4,5], 6)
        [0,1,2,3,4,5]
        """
        return arr[-1 * iterations:] + arr[0:-1 * iterations]

    k = k % len(a)
    a = rotateArrayRightCircular(a, k)
    res = []
    for n in queries:
        res.append(a[n])
    return res

上面的代码完成了我想要的,但是我必须将内部函数调用放在内部函数定义之后,这对我来说有点不雅。不同尝试的各种错误:

# trying 'self.inner()'
Traceback (most recent call last):
  File "solution.py", line 52, in <module>
    result = circularArrayRotation(a, k, queries)
  File "solution.py", line 13, in circularArrayRotation
    a = self.rotateArrayRightCircular(a, k)
NameError: name 'self' is not defined

# Removing 'self' and leaving the definition of inner() after the call to inner()
Traceback (most recent call last):
  File "solution.py", line 52, in <module>
    result = circularArrayRotation(a, k, queries)
  File "solution.py", line 13, in circularArrayRotation
    a = rotateArrayRightCircular(a, k)
UnboundLocalError: local variable 'rotateArrayRightCircular' referenced before assignment

知道如何在调用inner() 之后包含def inner()而不抛出错误吗?

【问题讨论】:

  • 总是必须定义函数(和其他变量)你使用它们...
  • 为什么你的rotateArrayRightCircular函数被定义在circularArrayRotation里面?为什么不直接在circularArrayRotation 之外定义它,然后如果您的目标是这样,那么您可以在之后拥有它。

标签: python function-call nested-function


【解决方案1】:

因为一个函数是自上而下执行的,一个函数随着函数的处理而存在,你想要的就是不可能的。

您可以将函数放在外部函数之前,使其本身成为外部函数,可能会添加一些参数(这里不是必需的)。 (顺便说一句,它看起来太通用了,代码的其他部分可能也想使用它,所以为什么不外层呢?)

但否则,您将陷入困境。和

中的情况基本相同
def f():
    print(a) # a doesn't exist yet, so this is an error
    a = 4

好吧,你可以这样做:

def circularArrayRotation(a, k, queries):

    def inner_code():
        k = k % len(a)
        a = rotateArrayRightCircular(a, k)

        # BTW, instead of the following, you could just do
        # return [a[n] for n in queries]
        res = []
        for n in queries:
            res.append(a[n])
        return res


    def rotateArrayRightCircular(arr: list, iterations: int) -> list:
        """
        Perform a 'right circular rotation' on an array for number of iterations.
        Note: function actually moves last 'iterations' elements of array to front of array.

        >>>rotateArrayRightCircular([0,1,2], 1)
        [2,0,1]

        >>>rotateArrayRightCircular([0,1,2,3,4,5], 3)
        [3,4,5,0,1,2]

        >>>rotateArrayRightCircular([0,1,2,3,4,5], 6)
        [0,1,2,3,4,5]
        """
        return arr[-1 * iterations:] + arr[0:-1 * iterations]

    return inner_code()

但我看不出你从中得到什么。

【讨论】:

    【解决方案2】:

    这在 Python 中是不可能的,但在 Javascript 和 PHP 等其他语言中是可能的。它被称为函数提升。

    【讨论】:

    • 谢谢,这就是我想知道的! :)