gpt4 book ai didi

python - 在其他函数中重新定义python函数

转载 作者:行者123 更新时间:2023-12-01 09:13:45 24 4
gpt4 key购买 nike

我可以弄清楚python的行为。这是代码示例:

def foo():
print('hello from initial foo')
def using_foo():
foo()
def wrapper(func):
def foo():
print('Now is overload foo')
print('Hello from wrapper')
func()
using_foo()
wrapper(using_foo)

这将打印:

hello from initial foo

Hello from wrapper

hello from initial foo

但我期望:

hello from initial foo

Hello from wrapper

Now is overload foo

因为下一个工作正常:

def foo():                                                                         
print('Hello from initial foo')
def using_foo():
foo()
using_foo()
if True:
def foo():
print('now it is overload foo')
using_foo()

输出:

Hello from initial foo

now it is overload foo

最佳答案

您只是错误地输入了 func() 而不是 foo():

def foo():
print('hello from initial foo')
def using_foo():
foo()
def wrapper(func):
def foo():
print('Now is overload foo')
print('Hello from wrapper')
foo()
using_foo()
wrapper(using_foo)

输出:

hello from initial foo
Hello from wrapper
Now is overload foo

关于python - 在其他函数中重新定义python函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51422537/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com