2017-10-28 3 views
0

例えば、私は私のコードがなりたい:関数にユーザー入力として名前を付けることはできますか?

として働くだろう
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 
+2

これを行うには多くの方法がありますが、それらのすべてが「CODE SMELL!」と叫びます。 –

+3

神の名前なぜ – 0TTT0

+0

それ以外の場合は、特定のユーザー入力の特定の関数を呼び出すことができます –

答えて

1
def hello(): 
    print('Hello!') 

fn_name = input('fn name: ') # input hello 
eval(fn_name)() # this will call the hello function 

警告:通常、これは良い習慣ではありませんが、これは一つの方法ですがあなたが求めていることをすること。

私は、各機能への参照を含む辞書を使用することになり
+1

これは一つの解決策ですが、望ましくないコードの実行を招く可能性があるため、 '' 'eval'''の使用は避けてください。 – chowmean

+0

@chowmean、私は同意します。それが私の警告を追加した理由です。 –

+0

はい、ソリューションに追加するだけでevalが何につながる可能性があります。ありがとう:) – chowmean

2

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! 
0

あなたすることができますが、本当にはいけない:これは、約提起奇妙な懸念と潜在的な問題があります。あなたが主張する場合は、実装は次のようになります。

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. 
0
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
この

という名前の関数
関連する問題