Python 3: creating a str object called

I have a Python program that accepts user input. I store user input of a string variable called userInput. I want to be able to call a string entered by a user ...

userInput = input("Enter a command: ")
userInput()

From this I get the error: TypeError: object 'str' cannot be called

I currently have a program that does something like this:

userInput = input("Enter a command: ")
if userInput == 'example_command':
    example_command()

def example_command():
     print('Hello World!')

Obviously, this is not a very efficient way to handle many commands. I want to make str obj callable - anyway to make it?

+4
source share
1 answer

A better method might be to use a dict:

def command1():
    pass

def command2():
    pass

commands = {
    'command1': command1,
    'command2': command2
}

user_input = input("Enter a command: ")
if user_input in commands:
    func = commands[user_input]
    func()

    # You could also shorten this to:
    # commands[user_input]()
else:
    print("Command not found.")

, literal , , , .

, local, , .., :

def command1():
    pass

def command2():
    pass

user_input = input("Enter a command: ")
if user_input in locals():
    func = locals()[user_input]
    func()

, , - , , .

+15

Source: https://habr.com/ru/post/1537249/


All Articles