I was wondering if you can make a function inside of another function in python. Just like this:
f().f2()
The f()
is the first function, and f2()
is the second function. Say f().f2()
prints out "Hello world"
. But if I change the .f2()
to .f3()
it will print another string of text.
Is it possible?
CodePudding user response:
Here's one approach:
def f():
class F:
@staticmethod
def f2():
print("Hello world")
@staticmethod
def f3():
print("Another string of text")
return F
f().f2()
f().f3()
CodePudding user response:
def f():
class F:
@staticmethod
def f_2():
print("something")
@staticmethod
def f_3():
print("something 2")
return F
f().f_2()
f().f_3()
CodePudding user response:
I like Samwise answer better, but here's a way of doing it without classes, if you really wanted to:
def f():
def f2():
print("Hello world")
def f3():
print("Another string of text")
for func_name, func in locals().items():
setattr(f, func_name, func)
return f
f().f2()
f().f3()