打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
如何在 Python 中调用函数?九种方法任你挑选
userphoto

2023.11.11 浙江

关注
机器学习与数据分析
2021-11-27 12:18

1.直接函数调用

这是最简单、最直观的方式:

def test(): print('This is a test') test()

2.使用partial()函数

在 的内置库中functools,有一个专用于生成偏函数的偏函数partial。

def power(x, n):
    s = 1
    while n > 0:
        n = n - 1
        s = s * x    return sfrom functools import partial

power_2 = partial(power, n=2)
power_2(3)  # output: 9power_2(4)  # output: 16

3. 使用 eval()

如果需要动态执行函数,可以使用 eval + string 来执行函数。

# demo.pyimport sysdef pre_task(): print('running pre_task')def task(): print('running task')def post_task(): print('running post_task') argvs = sys.argv[1:]for action in argvs: eval(action)()

执行:

$ python demo.py pre_task task post_taskrunning pre_taskrunning taskrunning post_task

4. 使用 getattr()

如果把所有的函数都放在类中,并定义为静态方法,就可以使用getattr()get和调用它们。

import sysclass Task: @staticmethod def pre_task(): print('running pre_task') @staticmethod def task(): print('running task') @staticmethod def post_task(): print('running post_task') argvs = sys.argv[1:] task = Task()for action in argvs: func = getattr(task, action) func()

5. 使用 __dict__()

我们都知道对象有一个__dict__()魔法方法,它存储任何对象的属性和方法。

您可以调用类方法使用__dict__.get

import sysclass Task:    @staticmethod
    def pre_task():
        print('running pre_task')


func = Task.__dict__.get('pre_task')
func.__func__()# Output$ python /tmp/demo.py
running pre_task

6. 使用 global()

在 的内置库中functools,有一个专用于生成偏函数的偏函数partial。

import sysdef pre_task(): print('running pre_task')def task(): print('running task')def post_task(): print('running post_task') argvs = sys.argv[1:]for action in argvs: globals().get(action)()# Output$ python /tmp/demo.py pre_task task post_task running pre_task running task running post_task

7. 从文本编译和运行

您可以在字符串中定义您的函数,并使用该compile函数将其编译为字节码,然后用于exec执行它。

pre_task = '''
print('running pre_task')
'''exec(compile(pre_task, '', 'exec'))# Or from a text filewith open('source.txt') as f:
    source = f.read()
    exec(compile(source, 'source.txt', 'exec'))

8. 使用attrgetter()

在 的内置库中operator,有一个获取属性的方法,称为attrgetter,获取函数后执行。

from operator import attrgetterclass People: def speak(self, dest): print('Hello, %s' %dest) p = People() caller = attrgetter('speak') caller(p)('Tony')# Output$ python /tmp/demo.py Hello, Tony

9. 使用methodcaller()

还有一个methodcaller方法在operator

from operator import methodcallerclass People:
    def speak(self, dest):
        print('Hello, %s' %dest)


caller = methodcaller('speak', 'Tony')
p = People()
caller(p)# Output$ python /tmp/demo.py
Hello, Tony
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Python征途--嵌套函数/嵌套作用域/闭包
python基础
Python之闭包与延时绑定问题
Python入门常识【入门必学】
Python语法基础
python知识巩固 | lambda函数表达式,玩转函数速写
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服