Movatterモバイル変換
[0]ホーム
def <dynamic function name> () syntax ?
Remco Gerlichscarblac at pino.selwerd.nl
Wed Apr 4 13:58:18 EDT 2001
Bruce Edge <bedge at troikanetworks.com> wrote in comp.lang.python:> Can the follwoing be accomplished in Python?>> I want to create a func named "abc":>> >>> name="abc">> >>> eval ("name")> 'abc'>> >>> def eval ("name") ():> File "<stdin>", line 1> def eval ("name") ():> ^> SyntaxError: invalid syntaxWell, deff tempfunc(): print wheeexec(name+" = tempfunc")del tempfuncWorks. But how would you use the function? Maybe it's easier to usesome dictionary, iedef tempfunc(): print wheefunction_dict = {name: tempfunc}del tempfunc# Run itfunction_dict[name]()If you want the function to be in some module, you can use setattr()to make it.import somemoduledef tempfunc(): print wheesetattr(somemodule, name, tempfunc)del tempfunc# Run itgetattr(somemodule, name)()But somehow I feel you don't need it anyway. Are you sure you're not tryingto port some idea from another language too literally? In Python you usuallydon't care about the name of the function when passing it to other things,as you can just pass the function itself...-- Remco Gerlich
More information about the Python-listmailing list
[8]ページ先頭