your programing

Python의 중첩 함수

lovepro 2020. 10. 11. 11:03
반응형

Python의 중첩 함수


다음과 같은 Python 코드로 얻을 수있는 이점 또는 의미 :

class some_class(parent_class):
    def doOp(self, x, y):
        def add(x, y):
            return x + y
        return add(x, y)

나는 이것을 오픈 소스 프로젝트에서 발견했고, 중첩 된 함수 내부에서 유용한 일을했지만 호출하는 것 외에는 아무것도하지 않았다. (실제 코드는 여기 에서 찾을 수 있습니다 .) 누군가 이렇게 코딩 할 수있는 이유는 무엇입니까? 외부의 일반 함수가 아닌 중첩 된 함수 내부에서 코드를 작성하는 데 따른 이점이나 부작용이 있습니까?


일반적으로 폐쇄 를 위해 수행합니다 .

def make_adder(x):
    def add(y):
        return x + y
    return add

plus5 = make_adder(5)
print(plus5(12))  # prints 17

내부 함수는 둘러싸는 범위 (이 경우 지역 변수 x) 에서 변수에 액세스 할 수 있습니다 . 둘러싸는 범위에서 변수에 액세스하지 않는 경우 실제로는 범위가 다른 일반 함수일뿐입니다.


내부 함수 생성이 거의 함수 생성기의 정의 인 함수 생성기를 제외하고 중첩 함수를 만드는 이유는 가독성을 높이기 위해서입니다. 외부 함수에 의해서만 호출되는 작은 함수가있는 경우 정의를 인라인하여 해당 함수가 수행하는 작업을 확인하기 위해 건너 뛸 필요가 없습니다. 나중에 함수를 재사용해야하는 경우 항상 내부 메서드를 캡슐화 메서드 외부로 이동할 수 있습니다.

장난감 예 :

import sys

def Foo():
    def e(s):
        sys.stderr.write('ERROR: ')
        sys.stderr.write(s)
        sys.stderr.write('\n')
    e('I regret to inform you')
    e('that a shameful thing has happened.')
    e('Thus, I must issue this desultory message')
    e('across numerous lines.')
Foo()

내부 메서드 사용의 잠재적 이점 중 하나는 인수로 전달하지 않고도 외부 메서드 지역 변수를 사용할 수 있다는 것입니다.

def helper(feature, resultBuffer):
  resultBuffer.print(feature)
  resultBuffer.printLine()
  resultBuffer.flush()

def save(item, resultBuffer):

  helper(item.description, resultBuffer)
  helper(item.size, resultBuffer)
  helper(item.type, resultBuffer)

다음과 같이 쓸 수 있습니다.

def save(item, resultBuffer):

  def helper(feature):
    resultBuffer.print(feature)
    resultBuffer.printLine()
    resultBuffer.flush()

  helper(item.description)
  helper(item.size)
  helper(item.type)

그런 코드에 대한 좋은 이유를 상상할 수 없습니다.

다른 Ops와 마찬가지로 이전 버전의 내부 기능에 대한 이유가있을 수 있습니다.

For example, this makes slightly more sense:

class some_class(parent_class):
    def doOp(self, op, x, y):
        def add(x, y):
            return x + y
        def sub(x,y):
            return x - y
        return locals()[op](x,y)

some_class().doOp('add', 1,2)

but then the inner function should be ("private") class methods instead:

class some_class(object):
    def _add(self, x, y):
        return x + y
    def doOp(self, x, y):
        return self._add(x,y)

The idea behind local methods is similar to local variables: don't pollute the larger name space. Obviously the benefits are limited since most languages don't also provide such functionality directly.


Are you sure the code was exactly like this? The normal reason for doing something like this is for creating a partial - a function with baked-in parameters. Calling the outer function returns a callable that needs no parameters, and so therefore can be stored and used somewhere it is impossible to pass parameters. However, the code you've posted won't do that - it calls the function immediately and returns the result, rather than the callable. It might be useful to post the actual code you saw.

참고URL : https://stackoverflow.com/questions/1589058/nested-function-in-python

반응형