自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Python函數(shù)調(diào)用的九大方法,鮮為人知

開發(fā) 前端
分享調(diào)用函數(shù)的9種方法:getattr, partial, eval, __dict__, globals, exec, attrgetter, methodcaller, 和 __call__。其中一些函數(shù)調(diào)用方法,在函數(shù)式編程或元編程場景中大量使用。相信你在今后的學(xué)習(xí)或工作中會遇到!

分享調(diào)用函數(shù)的9種方法:getattr, partial, eval, __dict__, globals, exec, attrgetter, methodcaller, 和 __call__。其中一些函數(shù)調(diào)用方法,在函數(shù)式編程或元編程場景中大量使用。相信你在今后的學(xué)習(xí)或工作中會遇到!

1. 直接調(diào)用函數(shù)(__call__)

最簡單最直接的使用方法:

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

func.__call__() # 一樣的

2. partial 函數(shù)

在python的內(nèi)置庫functools中有一個partial函數(shù),可以讓我們可以把一個函數(shù)的一部分參數(shù)填入,然后調(diào)用??雌饋頉]什么用,遇到的時候有大用。

from functools import partial
# 請仔細(xì)品!
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 函數(shù)

如果需要動態(tài)執(zhí)行函數(shù),可以使用 eval 來執(zhí)行動態(tài)代碼。

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) # 執(zhí)行函數(shù)
# running pre_task
# running task
# running post_task

4. getattr 函數(shù)

運行類中的靜態(tài)方法

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對象都有一個內(nèi)置的__dict__()方法,這個方法返回一個字典,包含了對象的所有屬性。如下圖,我們可以看到list的__dict__()方法返回的所有屬性,其中紅框內(nèi)的,你是否有些熟悉?

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 函數(shù)

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 函數(shù)

你可以在一個字符串中定義你的函數(shù),并使用compile函數(shù)將它編譯成字節(jié)碼,然后使用exec來執(zhí)行它。

# 方式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 函數(shù)

在內(nèi)置庫operator中,有一個獲取屬性的方法,叫做attrgetter,我們可以通過它獲取函數(shù)后執(zhí)行。

from operator import attrgetter

class People:
    def speak(self, dest):
        print("Hello, %s" %dest)

p = People()
caller = attrgetter("speak")
caller(p)("Tony") # Hello, Tony
# 本文第四條
caller2 = getattr(p, "speak")
caller2("Tony") # Hello, Tony

9. methodcaller 函數(shù)

from operator import methodcaller

class People:
    def speak(self, dest):
        print(f"Hello, {dest}")

caller = methodcaller("speak", "Tony")
p = People()
caller(p)

小節(jié)

總結(jié)下,本文分享了使用函數(shù)的9種方法:getattr, partial, eval, __dict__, globals, exec, attrgetter, methodcaller, 和 __call__。

請仔細(xì)品味,思考下他們的使用場景。其中一些函數(shù)調(diào)用方法,在函數(shù)式編程或元編程場景中大量使用。相信你在今后的學(xué)習(xí)或工作中會遇到!

責(zé)任編輯:華軒 來源: 哈希編程
相關(guān)推薦

2024-05-20 13:02:30

Python編程開發(fā)

2009-07-09 17:38:35

2022-07-19 08:46:15

NeofetchLinux

2010-01-07 10:05:51

IT顧問特質(zhì)

2023-09-26 12:34:29

Python迭代過濾函數(shù)

2011-05-03 13:13:52

編程PHPJava

2024-09-10 08:35:57

2024-06-05 10:35:24

Python字符串函數(shù)

2014-04-22 16:38:12

GitHubGitHub 使用技巧

2024-01-15 18:02:09

docker系統(tǒng)文件格式

2023-07-26 07:51:30

CSSgap 屬性

2021-08-03 09:55:37

Python函數(shù)編程語言

2021-07-07 10:59:48

python代碼編程語言

2018-12-10 19:30:45

2022-05-30 09:01:13

CSS技巧前端

2009-09-14 09:45:20

Chrome谷歌操作系統(tǒng)

2014-07-29 14:25:43

Unix命令

2019-10-08 16:24:33

Chrome瀏覽器

2023-04-23 15:11:26

2020-06-15 14:43:16

Python開發(fā)工具
點贊
收藏

51CTO技術(shù)棧公眾號