There are several options; you could use the getattr() function to turn strings into attributes on your instance; this includes access to methods:
class MyClass():
def __init__(self):
player_words = input()
player_words = player_words.lower().replace(' ', '_')
try:
getattr(self, player_words)()
except AttributeError:
print("Sorry, there is no such command")
def help_me(self):
print("To receive help...")
This translates 'Help me' into help_me and finds the corresponding method to call.
To list all the possible methods, you could use the inspect.getmembers() function, together with the inspect.ismethod() predicate function to list all methods your class offers; you'll have to filter these as you don't want to present the __init__ method to your visitor. Perhaps you could overload the __doc__ attribute for functions for this purpose; it contains the function documentation string:
from inspect import getmembers, ismethod
def is_documented_method(ob):
return ismethod(ob) and ob.__doc__
class MyClass():
def __init__(self):
available_methods = getmembers(self, is_documented_method)
help_info = [
(name.replace('_', ' ').title(), func.__doc__)
for name, func in available_methods]
for name, documentation in help_info:
print(name, documentation, sep=': ')
player_words = input()
player_words = player_words.lower().replace(' ', '_')
try:
getattr(self, player_words)()
except AttributeError:
print("Sorry, there is no such command")
def help_me(self):
"""Provide help on all commands"""
print("To receive help...")
def frob_the_foobar(self):
"""Frobbing the Foobar will ..."""
print("Frobbing the Foobar, sir!")
Demo of the latter:
>>> MyClass()
Frob The Foobar: Frobbing the Foobar will ...
Help Me: Provide help on all commands
help me
To receive help...
<__main__.MyClass object at 0x1114829e8>
>>> MyClass()
Frob The Foobar: Frobbing the Foobar will ...
Help Me: Provide help on all commands
Frob The Foobar
Frobbing the Foobar, sir!
<__main__.MyClass object at 0x111482b38>
input, and it's not clear why you do that in__init__. How wide a range of inputs is acceptable from the user? Could you create a method to tell them the valid inputs?