Is there a way I could access a function that is nested inside another function. For example, I have this block of code right here. For example, I did f().s()
but it did not work:
def f():
def s():
print(13)
Is there a way I could access a function that is nested inside another function. For example, I have this block of code right here. For example, I did f().s()
but it did not work:
def f():
def s():
print(13)
Yes, you can:
def f():
def s():
print(13)
return s
Then you can call:
>>> f()()
13
Or if you want to have f().s():
def f():
class S:
def s():
print(13)
return S
You need to specify that the second function is a global var, then you'd need to call the first function in order for Python interpreter to create that second function.
See below;
>>> def foo():
... global bar
... def bar():
... print("Hello world!")
...
>>> bar()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'bar' is not defined
>>> foo()
>>> bar()
Hello world!
>>>
you certainly could do something
def f():
def s():
print("S")
return s
f()()
you could also expose them in an internal dict
def f(cmd):
return {"s": lambda: do_something_s,"y": lambda: do_something_y}.get(cmd,lambda:invalid_cmd)()
then use f("s")
or f("y")
none of these are likely to be the correct solution to what you are actually trying to achieve ...