這是很危險的直接調用未知的用戶輸入。 允許的功能名單可以作爲鍵在字典中指向實際的功能:
def intercept():
print("Function intercept.")
user_functions = dict(
intercept=intercept,
# ...
)
user_input = input("Input function name: ") # Python 3, raw_input for Python 2
if user_input in user_functions:
user_functions[user_input]()
else:
print("Error: Unknown function.")
結果:
$ python3 test.py
Input function name: intercept
Function intercept.
$ python3 test.py
Input function name: foobar
Error: Unknown function.
功能也可以動態創建,如:
def intercept():
print("Function intercept.")
def jimmy():
print("Function Jimmy.")
user_functions = {
'intercept': intercept,
# ...
}
def create_new_profile(name):
print("Creating profile for " + name)
def profile_function():
print("Profile " + name)
user_functions[name] = profile_function
while 1:
user_input = input("Input function name: ")
if user_input in user_functions:
user_functions[user_input]()
else:
create_new_profile(user_input)
print()
結果:
$ python3 test.py
Input function name: intercept
Function intercept.
Input function name: Jimmy
Creating profile for Jimmy
Input function name: Alice
Creating profile for Alice
Input function name: Alice
Profile Alice
Input function name: Bob
Creating profile for Bob
Input function name: Bob
Profile Bob
Input function name: Alice
Profile Alice
我不知道,「檔案功能」應該做什麼。也許,數據驅動的方法可能會更好。字典將用戶名映射到用戶數據。如果用戶輸入名稱不在配置文件字典中,則調用功能create_new_profile
以添加新用戶。以下示例將用戶數據實現爲包含正在運行的函數的類。
class UserProfile:
def __init__(self, name):
self.name = name
def run(self):
print("User: " + self.name)
def intercept():
print("Function intercept.")
user_profiles = {
'Jimmy' : UserProfile('Jimmy'),
}
def create_new_profile(name):
print("Creating new profile for " + name)
user_profiles[name] = UserProfile(name)
user_functions = {
'intercept': intercept,
# ...
}
while 1:
user_input = input("Input function name: ")
if user_input in user_functions:
user_functions[user_input]()
elif user_input in user_profiles:
user_profiles[user_input].run()
else:
create_new_profile(user_input)
print()
$ python3 test.py
Input function name: intercept
Function intercept.
Input function name: Jimmy
User: Jimmy
Input function name: Alice
Creating new profile for Alice
Input function name: Alice
User: Alice
[調用模塊從Python中的函數名稱的字符串的函數(http://stackoverflow.com/questions/3061/calling-a-function-of-的可能的複製一個模塊從一個字符串與函數名稱在Python中) –