Home > Blockchain >  Python call object function from user input
Python call object function from user input

Time:05-31

I got a question of how I can call a function of an object.
Here is how I can call a function with userinput:

Player1 = Player()
Player2 = Player()

INPUT = input()
if INPUT in locals().keys():
            try:
                print(locals()[INPUT]())

but I want to call for example Player1.status() (You dont need to know what it does, I just want to call it)
It doesnt work and I know why it doesnt work but how does it work?
And calling Player1 makes no sense obviously.

CodePudding user response:

Try using getattr(object, name[, default]) like this:

class Player:
    def status(self):
        return "Active"

player1 = Player()
INPUT = 'player1.status'

input_list = INPUT.split('.')

method_to_call = locals()[input_list[0]]
for i in input_list[1:]:
    method_to_call = getattr(method_to_call, i)

method_to_call()
  • Related