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.
1 Answer 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()
answered May 29, 2022 at 15:03
Mehrdad Pedramfar
11.1k4 gold badges43 silver badges61 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
chepner
I think the input indicates which object to use, not which method on an object.
Mehrdad Pedramfar
@chepner Just fixed it.
lang-py
dictorlistinstead of individually numbered variables andlocals()."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.