+ 16
[🐍PyTricks]: Functions are first-class citizens in Python
# Functions are first-class citizens in Python: # They can be passed as arguments to other functions, # returned as values from other functions, and # assigned to variables and stored in data structures. >>> def myfunc(a, b): ... return a + b ... >>> funcs = [myfunc] >>> funcs[0] <function myfunc at 0x107012230> >>> funcs[0](2, 3) 5
8 Réponses
+ 21
Тимофей Антонов
here is an example:
def func1(x,y):
print(x+y)
def func2(x,y):
print(x-y)
def func3(x,y):
print(x*y)
myfuncs=[func1,func2,func3]
a,b=2,3
for func in myfuncs:
func(a,b)
+ 8
In Javascript too, they are 1st class citizens. You should submit these as lessons from lesson factory instead of randomly posting as a post.
https://www.sololearn.com/discuss/1082512/?ref=app
+ 6
I've seen a lot of things in my life, but I've never seen functions being treated like that. Push it into an array! What are you allowing yourself, sir ?!
+ 2
It's really helpful, thanks.
+ 1
assigned to variables and stored in data structures.
>>> def myfunc(a, b):
... return a + b
...
>>> funcs = [myfunc]
>>> funcs[0]
<function myfunc at 0x107012230>
>>> funcs[0](2, 3)
5
0
def sums(x,y):
return x+y
def do_w(z,x,y):
return z(z(x,y),z(x,y))
a=12
b=15
print (do_w(sums,a,b))
0
It usually helps for code reuse (less code)
0
Тимофей Антонов thank you!! This makes it easy to understand