[英]Difficulty Understanding Nested functions in Python
我仍在尝试了解Python的基础知识,并试图弄清楚如何在内部函数action2
中将值附加到y
。
def outer(n):
def action(x):
return x ** n
def action2(y):
return x/n
return action2
return action
f = outer(2) #We are actually setting the n in action here
print(f)
print(f(5)) #We are now setting the x parameter in the inner function action
print(f(4))
g = outer(3)
print(g(3))
print(f(3)
谢谢
像这样嵌套函数的通常原因是为了进行函数修饰。 几个月前,我问了一个问题 ,答案似乎几乎完全适合您的用例。 本质上,您正在尝试执行以下操作:
def outer(n):
def action(x):
def action2(y):
return x**n / y
return action2
return action
这有点奇怪
def action(n, x, y):
return x**n / y
但是,我们会坚持下去。 无论如何,让我们返回规范函数装饰器,看看它如何进行比较。
def decorator(func):
def wrapped(*args, **kwargs):
print("Calling inner function")
return func(*args, **kwargs)
return wrapped
@decorator
def foo(some_txt):
print("Hello, ", some_txt)
# EXAMPLE OUTPUT
>>> foo("World!")
Calling inner function
Hello, World!
对于您要执行的操作来说,这一层太浅了。 如果我们回到前面链接的问题,我们将讨论一个验证器。
max_len_12 = lambda n: len(n) <= 12 # 12 character max field length
def validation(v):
"""ensures the result of func passes a validation defined by v"""
def outer(func):
def inner(*args, **kwargs):
while True:
result = func(*args, **kwargs)
# if validation passes
if v(result):
return result
return inner
return outer
@validation(max_len_12)
def valid_input(prompt):
return input(prompt)
# EXAMPLE
>>> valid_input("Enter your name (max 12 chars): ")
Enter your name (max 12 chars): Adam YouBetYourAss Smith
Enter your name (max 12 chars): Adam Smith
'Adam Smith'
或更容易地:
valid_input = validation(max_len_12)(raw_input)
# same as previous function
由于很难从示例代码中确切了解您要执行的操作,因此希望在装饰和闭包方面,您有一个很好的立足点。 请注意,要使您的功能能够自省,您需要做很多事情,其中大部分可以由functools.wraps
我假设您正在尝试完成以下任务:
def outer(n):
def action(x):
def action2(y):
return x ** n / y
return action2
return action
现在,您的测试命令将给出:
>>> f = outer(2)
>>> print f
<function action at 0x7f59b872e578>
>>> print f(5)
<function action2 at 0x7f59b872e5f0>
>>> print f(4)
<function action2 at 0x7f59b872e5f0>
f
是外部“关闭”,它本身是返回内部关闭的“工厂”功能。
>>> g = outer(3)
>>> print g(3)
<function action2 at 0x7f59b872e668>
现在,您有两个完全独立的函数f
和g
。
>>> print f(3)
<function action2 at 0x7f59b872e668>
…并且您可以像以前一样继续使用f
,这可能不是您想要的。
您可以这样调用内部闭包:
>>> f5 = f(5)
>>> print f5(10.)
2.5
或者您可以完全跳过变量:
>>> outer(3)(10)(2)
500
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.