Is there a way to write that function with a string that contains the function name?

Asked 2 years ago, Updated 2 years ago, 16 views

For example, mystring = "extend" And when you want to use the extend function with this

mystring = "extend"
a = [1,2,3]

myfunc = which function (a, mystring) # Now myfunc is the same role as a.extend
Same as myfunc([4]) #a.extend([4])
print a

Result: [1,2,3,4]

So that you can write it like this.

python

2022-09-21 19:21

1 Answers

Try getattr() It can be written as follows:

a = [1,2,3]
myfunc = getattr(a, 'extend') #Now myfunc is the same as a.extend()
myfunc([4]) # = a.extend([4])

#If you shorten the code above,
a = [1,2,3]
getattr(a, 'extend')([4])


2022-09-21 19:21

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.