gpt4 book ai didi

python - 在 Python 中调用嵌套函数

转载 作者:太空宇宙 更新时间:2023-11-04 09:54:44 25 4
gpt4 key购买 nike

是否可以调用在现有函数内定义的嵌套函数:

例如:

def first(x):
def second():
print(x)
return second

我知道我可以做这样的事情:first(10)()

但我想做类似的事情:

first(10).second()

我的想法是这是不可能的,因为在调用 first 之前 second 不存在。

我说得对吗?

最佳答案

如果你愿意,你可以用这种方式返回几个函数:

class Box(object):
def __init__(self,**kw): vars(self).update(kw)
def first(x):
def second():
print(x)
def third(y): return x+y
return Box(second=second,third=third)

first(10).second() # prints 10
x=first(15)
x.second() # prints 15
print(x.third(10)) # prints 25

答案的信誉分数如有雷同,纯属巧合。

关于python - 在 Python 中调用嵌套函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46362040/

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