简体   繁体   中英

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)()

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.

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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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