簡體   English   中英

Python:從external()調用inner()

[英]Python: calling inner() from outer()

我四處張望,令人驚訝的是找不到這個問題的答案。 我認為這是因為通常將內部/嵌套函數用於某些特定的事物(例如,維護環境變量,工廠),而不是像我試圖將其用於瑣碎的事物。 在任何情況下,我似乎無法找到如何正確地從外部函數中調用內部函數的任何信息,而不必申報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

知道如何在調用def inner() 之后包含def inner() inner()而不拋出錯誤嗎?

由於函數是從上到下執行的,並且隨着函數的處理而存在,所以根本無法實現所需的功能。

您可以將函數放在外部函數之前,使其成為外部函數,可能會添加一些參數(此處不必要)。 (順便說一句,它看起來是如此通用,代碼的其他部分也可能想要使用它,所以為什么不使用外部代碼呢?)

但是,否則,您將陷入困境。 情況與

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()

但我看不到您從中獲得任何收益。

這在Python中是不可能的,但在其他語言(如Javascript和PHP)中是可能的。 這稱為功能提升。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM