如何动态调用Python函数 [英] How to call Python functions dynamically

查看:96
本文介绍了如何动态调用Python函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

  fields = ['name','email'] 

def clean_name():
传递

def clean_email():
传递

如何动态地调用 clean_name() clean_email()



例如:

 字段中的字段:
clean_ {我使用了大括号,因为这是我以前用PHP做的,但显然 如果不想使用全局变量,变量,并且不想使用独立的模块和/或类来封装要动态调用的函数,则可以调用它们作为当前模块的属性:

pre $ $ $ c $ import

getattr(sys。模块[__ name__],clean_%s%fieldname)()


I have this code:

fields = ['name','email']

def clean_name():
    pass

def clean_email():
    pass

How can I call clean_name() and clean_email() dynamically?

For example:

for field in fields:
    clean_{field}()

I used the curly brackets because it's how I used to do it in PHP but obviously doesn't work.

How to do this with Python?

解决方案

If don't want to use globals, vars and don't want make a separate module and/or class to encapsulate functions you want to call dynamically, you can call them as the attributes of the current module:

import sys
...
getattr(sys.modules[__name__], "clean_%s" % fieldname)()

这篇关于如何动态调用Python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆