Gagantous
Gagantous

Reputation: 518

Input user considered as method rather than just a common string in python

I tried to make a simple program using python that take custom input from user and it would used into a list which have a input format like this.

$ python name_app.py
$ <method> <position_index> <value>

i have tried some thing like this.

 lst = []
 n = input().split()
 print(n[0])
 test = lst.n[0](n[1], n[2])
 print(test)

The sample input would be like:

$ python name_app.py
$ append 0 2

Well i thought the code would be like this if i pass the input

lst.append(0, 2)

But i got an error like below

File "app.py", line 5, in arr                                                                                                                 
    test = lst.n[0](n[1], n[2])                                                                                                                 
AttributeError: 'list' object has no attribute 'n'  

How could i make the user's input considered as "method" object and not a common attribute ?

Upvotes: 0

Views: 32

Answers (2)

Kevin
Kevin

Reputation: 30151

You're looking for getattr():

test = getattr(lst, n[0])(n[1], n[2])

But then you're going to run into the problem that both n[1] and n[2] are strings, not ints. So you'll need to pass them through int() to parse them. Also, you probably won't be able to pass two arguments to the list.append() method, because it only takes one.

Finally, I think you may find the cmd module a more convenient way of converting user input into method calls, instead of using getattr() directly.

Upvotes: 1

kamses
kamses

Reputation: 465

You can use getattr() to call a method of list, or any module or class, from a user provided string.

lst = []   
n = input().split()
getattr(lst, n[0])(n[1])
print(lst)

Append the number 5 to the list like so:

$ python name_app.py
$ append 5
$ [5]

Upvotes: 1

Related Questions