简体   繁体   English

在Python中调用嵌套函数

[英]Call a nested function in Python

Is it possible to call a nested function defined inside an existing function: 是否可以调用在现有函数内部定义的嵌套函数:

For example: 例如:

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

I know I can do something like this: first(10)() 我知道我可以做这样的事情: first(10)()

Yet I want to do something similar to this: 但是我想做类似的事情:

first(10).second()

My thinking is that it is not possible because second does not exist until first is called. 我的想法是不可能的,因为在调用first之前, second不存在。

Am I right? 我对吗?

Why not use a class? 为什么不使用课程?

class First:
    def __init__(self, x):
        self.x = x

    def second(self):
        print(x)

First(3).second()

The fact that all Python functions are closures is a great feature, but it's fairly advanced. 所有Python函数都是闭包的事实是一个很棒的功能,但是相当先进。 Classes are the usual place to store state. 类是存储状态的通常位置。

Though it is not the right way but just for fun. 虽然这不是正确的方法,但只是为了好玩。 What you are doing here is returning the instance of the second function, so while calling it, no dont need to call it by name, jsut use the variable. 您在这里所做的是返回第二个函数的实例,因此在调用它时,不需要按名称调用它,而是使用该变量。

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

    return second

x = first(10)
x()

or like this 或像这样

first(10)()

as mention by other, use class instead. 就像其他人提到的那样,使用class代替。

If you want, you can return several functions that way: 如果需要,可以以这种方式返回几个函数:

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

Any resemblance to reputation scores for answers is coincidental. 与答案的声誉得分的任何相似之处都是偶然的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM