다른 대답을 잘 설명하지만, 여기에 코드에서이 객체로 함수의 개념 이해
def makeInc(x): # define a function makeInc that takes a variable x
# when makeInc is executed, define a function "inc" that takes a variable y
def inc(y):
# when inc is executed, return the sum (where x is closed in the outer function)
# note this is not executed when makeInc is called
return y + x
# don't call inc yet, just return a reference to the function itself - note there
# are no parenthesis after inc
return inc
inc5 = makeInc(5) # now execute makeInc which returns a reference to the inc function
# with the variable x captured by the closure
inc5(12) # now call the result of the above which is the only place that we call inc
# note the parenthesis to designate the function call
# print inc5(12) gives 17
중앙 무슨 라인 고장에 의하여 선이다. 파이썬에서이 작업을 수행 할 수 있습니다
makeInc
가 호출
>>> def test(x):
... return x + 6
...
>>> test(1) # call test with the argument x = 1
7
>>> a = test # assign the function "test" to a new variable "a" - this is not calling test
>>> a
<function test at 0x101cfbb90> # printing a shows the original function name "test"
>>> a(1) # now call that function again with the same value for x = 1
7
, 그것은 (Y라는 주장을 복용) 다른 기능의 서명이있는 내 inc
에 대한 참조를 반환합니다. 둘 다 단일 인수를 취한다는 사실은 적합하지 않습니다.
코드를 실행하면 'inc5 (12)'의 결과가 17이됩니다. –
죄송합니다. 17, 올바르게 수정합니다 – redenigma
코드에서 한 번만 inc5를 호출합니다. "첫 번째 호출"은 완전히 별도의 함수 인'makeInc'입니다. –