0

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.

3
  • 1
    Use an explicit dict or list instead of individually numbered variables and locals(). Commented May 29, 2022 at 15:04
  • But "It doesnt work" is not a good description of the symptoms. Also, you should break down your last line into separate concepts so you can tell what you mean. Commented May 29, 2022 at 15:14
  • 1
    The user of your program should not need to know the name of the method it wants to call. The mapping between the user's input and the method it will trigger should be in your code, not your user's head. Commented May 29, 2022 at 15:16

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

2 Comments

I think the input indicates which object to use, not which method on an object.
@chepner Just fixed it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.