Python函数调用的九大方法,鲜为人知_python调用方法

1. 直接调用函数(__call__

最简单最直接的使用方法:

def func():
    print('Hello, world!')
func() # Hello, world!

func.__call__() # 一样的

2. partial 函数

在python的内置库functools中有一个partial函数,可以让我们可以把一个函数的一部分参数填入,然后调用。看起来没什么用,遇到的时候有大用。😊😊

from functools import partial
# 请仔细品!
def func(domain, user):
    echo = f"Hello, {user}@{domain}!"
    print(echo)


func_userA = partial(func, user="userA")
func_userB = partial(func, user="userB")
func_userA("example.com") # Hello, userA@example.com!
func_userB("example.com") # Hello, userB@example.com!

3. eval 函数

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

import sys
def pre\_task():
    print("running pre\_task")

def task():
    print("running task")

def post\_task():
    print("running post\_task")

cmdList = ["pre\_task()","task()","post\_task()"]
for cmd in cmdList:
    eval(cmd) # 执行函数
# running pre\_task
# running task
# running post\_task

4. getattr 函数

运行类中的静态方法

import sys


class Task:
    @staticmethod
    def pre\_task():
        print("running pre\_task")

    @staticmethod
    def task():
        print("running task")

    @staticmethod
    def post\_task():
        print("running post\_task")

#⚠️ 没有括号的字符串。
cmdList = ["pre\_task", "task", "post\_task"]

task = Task()

for cmd in cmdList:
    func = getattr(task, cmd)
    func()

5. dict 方法

首先我们需要知道,每个python对象都有一个内置的__dict__()方法,这个方法返回一个字典,包含了对象的所有属性。
如下图,我们可以看到list的__dict__()方法返回的所有属性,其中红框内的,你是否有些熟悉?

2

class Task:
    @staticmethod
    def pre\_task():
        print("running pre\_task")

    @staticmethod
    def task():
        print("running task")

    @staticmethod
    def post\_task():
        print("running post\_task")


func = Task.__dict__.get("pre\_task")
func.__func__() # running pre\_task
func() # 为什么不这样用?

6. globals 函数

import sys

def pre\_task():
    print("running pre\_task")

def task():
    print("running task")

def post\_task():
    print("running post\_task")

cmdList = ["pre\_task", "task", "post\_task"]

for cmd in cmdList:
    func = globals().get(cmd)
    func()
# running pre\_task
# running task
# running post\_task

7. exec 函数

你可以在一个字符串中定义你的函数,并使用compile函数将它编译成字节码,然后使用exec来执行它。

# 方式1
pre_task = """
print("running pre\_task")
"""
exec(compile(pre_task, '', 'exec'))
# running pre\_task

# 方式2
with open('./source.txt') as f:
    source = f.read()
    exec(compile(source, 'source.txt', 'exec'))

8. attrgetter 函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值