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?
Samwise :
Here's one approach:\ndef f():\n class F:\n @staticmethod\n def f2():\n print("Hello world")\n\n @staticmethod\n def f3():\n print("Another string of text")\n return F\n\n\nf().f2()\nf().f3()\n",
2021-10-18T13:54:28
luther :
The other answers are good, but a simpler solution would be to make f a class. Since classes are callable, you can basically treat them as functions. The dot in f().f2() implies that f must return an object with an f2 attribute, and a class can do just that:\nclass f:\n\n def f2(self):\n print("Hello world")\n\n def f3(self):\n print('another string of text')\n",
2021-10-18T17:14:04
rv.kvetch :
I like Samwise answer better, but here's a way of doing it without classes, if you really wanted to:\ndef f():\n def f2():\n print("Hello world")\n\n def f3():\n print("Another string of text")\n\n for func_name, func in locals().items():\n setattr(f, func_name, func)\n\n return f\n\n\nf().f2()\nf().f3()\n",
2021-10-18T14:01:38