例如,我想我的代碼是:你可以將一個函數命名爲用戶輸入嗎?
name_of_function = input("Please enter a name for the function: ")
def name_of_function():
print("blah blah blah")
這將作爲工作:
Please enter a name for the function: hello
>>>hello()
blah blah blah
例如,我想我的代碼是:你可以將一個函數命名爲用戶輸入嗎?
name_of_function = input("Please enter a name for the function: ")
def name_of_function():
print("blah blah blah")
這將作爲工作:
Please enter a name for the function: hello
>>>hello()
blah blah blah
我會用包含每個函數引用的字典:
def func_one():
print("hello")
def func_two():
print("goodbye")
def rename_function(func_dict, orig_name, new_name):
func_dict[new_name] = func_dict[orig_name]
del func_dict[orig_name]
functions = {
"placeholder_one": func_one,
"placeholder_two": func_two
}
rename_function(
functions,
"placeholder_one",
input("Enter new greeting function name: ")
)
rename_function(
functions,
"placeholder_two",
input("Enter new farewell function name: ")
)
while True:
func_name = input("Enter function to call: ")
if func_name in functions:
functions[func_name]()
else:
print("That function doesn't exist!")
用法:
>>> Enter new greeting function name: hello
>>> Enter new farewell function name: goodbye
>>> Enter function to call: hello
hello
>>> Enter function to call: goodbye
goodbye
>>> Enter function to call: hi
That function doesn't exist!
您可以,但你真的不應:這就對一百多個奇怪的問題和潛在的問題。但是,如果你堅持,實施將看起來像下面這樣:
def define_function(scope):
name_of_function = input("Enter a name for the function: ")
function_body = """def {}():
print("Blah blah blah.")
""".format(name_of_function)
exec(function_body, scope)
如果從Python外殼,如果導入包含此功能(在我的情況,sandbox.py
)文件,並通過globals()
或locals()
它,你可以很暫時得到你想要的接口。
>>> from sandbox import *
>>> define_function(globals())
Enter a name for the function: hello
>>> hello()
Blah blah blah.
class Foo(object):
def foo1(self):
print ('call foo1')
def foo2(self):
print ('call foo2')
def bar(self):
print ('no function named this')
def run(func_name):
funcs = Foo()
try:
func = getattr(funcs, func_name)
except Exception as ex:
funcs.bar()
return
func()
func_name = raw_input('please input a function name:')
run(func_name)
用法:
請輸入函數名稱:foo1
呼叫foo1請輸入函數名稱:foo3
功能
沒有名爲此
有很多方法可以做到這一點,但是他們都尖叫着「CODE SMELL!」。 –
在gods的名字爲什麼你會想要這樣做 – 0TTT0
否則,你可以調用特定的功能爲特定的用戶輸入 –