最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python動(dòng)態(tài)加載技術(shù)解析

 更新時(shí)間:2023年07月10日 08:32:01   作者:祁華平  
這篇文章主要介紹了python動(dòng)態(tài)加載技術(shù)解析,說簡單點(diǎn)就是,如果開發(fā)者發(fā)現(xiàn)自己的代碼有bug,那么他可以在不關(guān)閉原來代碼的基礎(chǔ)之上,動(dòng)態(tài)替換模塊替換方法一般用reload來完成,需要的朋友可以參考下

前言

提到python動(dòng)態(tài)加載技術(shù),我們需要聊上幾個(gè)話題:

1)反射技術(shù)

2)模塊動(dòng)態(tài)加載importlib

3)  callback(函數(shù)名傳遞)--不完全算是吧動(dòng)態(tài)

反射技術(shù)

先說反射技術(shù),所謂反射技術(shù)就是指的是在程序的運(yùn)行狀態(tài)中,對于任意一個(gè)類,都可以知道這個(gè)類的所有屬性和方法;對于任意一個(gè)對象,都能夠調(diào)用他的任意方法和屬性,增加刪除方法和屬性。這種動(dòng)態(tài)獲取程序信息以及動(dòng)態(tài)調(diào)用對象的功能稱為反射機(jī)制。

步驟:

class Animal:
    def __init__(self, name, legs) -> None:
        self.name = name
        self.legs = legs
    def get_legs(self):
        return self.legs
    def get_name(self):
        return self.name
animal = Animal('dog', 4)
print(dir(animal))
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'get_legs', 'get_name', 'legs', 'name']

具體一個(gè)應(yīng)用場景,比如我們的testcase來自一個(gè)文本的創(chuàng)建的一個(gè)測試計(jì)劃,其中是一個(gè)所要執(zhí)行的測試用例的list

['test_test1', 'test_test2',...]

我們要執(zhí)行它,比如我的測試實(shí)例是test_obj

class T1:
    def test_test11(self):
        print('test11')
    def test_test22(self):
        print('test22')
class Test(T1):
    def test_test1(self):
        print('test1')
    def test_test2(self):
        print('test2')
test_obj = Test()
for test in [ 'test_test1',  'test_test2', 'test_test11', 'test_test22']:
    method = getattr(test_obj, test) # 如果該函數(shù)不存在會raise exception
    method()
# 可以修改如下
test_obj = Test()
for test in [ 'test_test1',  'test_test2', 'test_test11', 'test_test22']:
    method = getattr(test_obj, test, lambda :'donothing') # 如果不存在就運(yùn)行一個(gè)匿名函數(shù),實(shí)際就是一個(gè)默認(rèn)值
    method()

反射中的setattr等不在本次討論的范疇。

模塊動(dòng)態(tài)加載importlib

動(dòng)態(tài)加載模塊,可以用于,當(dāng)我們已經(jīng)知道我們的模塊名稱,在我們的目的是動(dòng)態(tài)加載這些module用于運(yùn)行;動(dòng)態(tài)加載指在程序運(yùn)行中,動(dòng)態(tài)的加載模塊,而不是在運(yùn)行之前利用import 或from ... import 的方式加載模塊的方式。

應(yīng)用場景:

(1) 程序在運(yùn)行期間才能確定加載的模塊。

(2) 在某種條件下,需要通過模塊名字符串進(jìn)行加載的模塊。

#mymodule/mytest.py
def helloworld():
    print('hello world')
class MyModule:
    def print_hello(self):
        print(f'hello from {self.__class__}')
# test.py
import importlib
def import_method1():
    """From module"""
    module = importlib.import_module('mymodule.mytest')
    module.helloworld()
    my_module_obj = module.MyModule()
    my_module_obj.print_hello()
def import_method2():
    """From file path"""
    file = 'mymodule/mytest.py'
    module_name = 'mytest'
    # loading module
    spec = importlib.util.spec_from_file_location(module_name, file)
    module = importlib.util.module_from_spec(spec)
    #execute module
    spec.loader.exec_module(module) 
    # invoke methods
    module.helloworld()
    my_module = module.MyModule()
    my_module.print_hello()

另外一個(gè)例子,我們的module中有很多個(gè)類,相同的方法,這樣我們可以批處理進(jìn)行調(diào)用

# mytest/myfile.py
import sys
class Test1:
    def setup(self):
        print(f" {self.__module__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}")
    def teardown(self):
        print(f" {self.__module__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}")
    def run(self):
        print(f" {self.__module__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}")
class Test2:
    def setup(self):
        print(f" {self.__module__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}")
    def teardown(self):
        print(f" {self.__module__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}")
    def run(self):
        print(f" {self.__module__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}")
# test.py
import importlib
libs = 'mytest.myfile'
class_names = ['Test1', 'Test2']
methods = ['setup', 'run', 'teardown', 'hello'] # hello不存在的
my_import = importlib.import_module(libs)
for cls_ in class_names:
    Clss = getattr(my_import, cls_) # 獲取模塊下的類
    my_class = Clss() # 實(shí)例化
    for m in methods:
        method = getattr(my_class, m, lambda: "DoNothing") # 獲取類方法, 默認(rèn)lambda為了防止函數(shù)不存在
        method() #  執(zhí)行方法
# output
 mytest.myfile.Test1.setup
 mytest.myfile.Test1.run
 mytest.myfile.Test1.teardown
 mytest.myfile.Test2.setup
 mytest.myfile.Test2.run
 mytest.myfile.Test2.teardown

另外一種方式:

通過__import__加載

函數(shù)原型:__import__(name, globals={}, locals={}, fromlist=[], level=-1)

  參數(shù):name:模塊名,包含路徑

       globals:全局變量,一般默認(rèn),如果設(shè)置,可設(shè)置globals()

       locals:局部變量,一般默認(rèn),如果設(shè)置,可設(shè)置locals()

     fromlist:導(dǎo)入的模塊,及name下的模塊名、函數(shù)名、類名或者全局變量名。

  返回值:module對象,通過取module得屬性獲取模塊得函數(shù)、類或者全局變量等。

# 如上代碼,我們下面的方式
d1 = __import__(libs)
for cls_ in class_names:
    Clss = getattr(my_import, cls_) # 獲取模塊下的類
    my_class = Clss() # 實(shí)例化
    for m in methods:
        method = getattr(my_class, m, lambda: "DoNothing") # 獲取類方法
        method() #  執(zhí)行方法

另外一種方式:通過exec進(jìn)行,但是不建議用邪惡的exec

import_string = "import mytest.myfile as myfile"
exec(import_string )
t1 = myfile.Test1()
t1.setup()

callback方式(回調(diào))

說到回調(diào)不得不提python的函數(shù)其實(shí)也是一種類型

比如你可以將一個(gè)函數(shù)名給一個(gè)變量

比如最常見的匿名函數(shù)

squre = lambda x: x*x
squre(5)
25

那么回調(diào)就是我們在執(zhí)行一個(gè)函數(shù)時(shí)候,另外一個(gè)函數(shù)作為一個(gè)變量傳入,以便對在該函數(shù)中由系統(tǒng)在符合你設(shè)定的條件時(shí)自動(dòng)調(diào)用

def my_function(a, b, callback_func):
??????? ....
??????? if xxx:
??????????????? callback_func(**kwargs)

 這里不給贅述了,僅僅該一個(gè)例子,比如我們在實(shí)時(shí)讀取文件的時(shí)候進(jìn)行查找默寫匹配的

import time
import re
def follow_file_with_timeout(tailed_file,callback_func, timeout=10):
    with open(tailed_file) as file_:
        file_.seek(0,2) # Go to the end of file
        start_time = time.time()
        while time.time() - start_time < timeout:
            curr_position = file_.tell()
            line = file_.readline()
            if not line:
                file_.seek(curr_position)
                time.sleep(1)
            else:
                callback_func(line)
def my_search(line):
    if line:
        matched = re.search('Yourpatternhear', line)
        if matched:
            print(line)
follow_file_with_timeout('test.txt', my_search)

到此這篇關(guān)于淺談一下python動(dòng)態(tài)加載技術(shù)的文章就介紹到這了,更多相關(guān)python動(dòng)態(tài)加載內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • python pandas多條件篩選實(shí)現(xiàn)方式

    python pandas多條件篩選實(shí)現(xiàn)方式

    用戶在使用pandas進(jìn)行多條件篩選時(shí)發(fā)現(xiàn)無現(xiàn)成方法,自行編寫函數(shù)實(shí)現(xiàn),數(shù)據(jù)為虛構(gòu),供參考學(xué)習(xí),鼓勵(lì)支持腳本之家
    2025-09-09
  • 在pycharm中輸入import torch報(bào)錯(cuò)如何解決

    在pycharm中輸入import torch報(bào)錯(cuò)如何解決

    這篇文章主要介紹了在pycharm中輸入import torch報(bào)錯(cuò)如何解決問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-01-01
  • 對numpy中的transpose和swapaxes函數(shù)詳解

    對numpy中的transpose和swapaxes函數(shù)詳解

    今天小編就為大家分享一篇對numpy中的transpose和swapaxes函數(shù)詳解,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-08-08
  • 用python查找統(tǒng)一局域網(wǎng)下ip對應(yīng)的mac地址

    用python查找統(tǒng)一局域網(wǎng)下ip對應(yīng)的mac地址

    這篇文章主要介紹了用python查找統(tǒng)一局域網(wǎng)下ip對應(yīng)的mac地址的示例代碼,幫助大家更好的理解和使用python,感興趣的朋友可以了解下
    2021-01-01
  • Python字符串本身作為bytes進(jìn)行解碼的問題

    Python字符串本身作為bytes進(jìn)行解碼的問題

    這篇文章主要介紹了解決Python字符串本身作為bytes進(jìn)行解碼的問題,文末給大家補(bǔ)充介紹了,Python字符串如何轉(zhuǎn)為bytes對象?Python字符串和bytes類型怎么互轉(zhuǎn),需要的朋友可以參考下
    2022-11-11
  • Python安裝Scrapy庫的常見報(bào)錯(cuò)解決

    Python安裝Scrapy庫的常見報(bào)錯(cuò)解決

    本文主要介紹了Python安裝Scrapy庫的常見報(bào)錯(cuò)解決,文中通過圖文示例介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-11-11
  • 從基礎(chǔ)到高級詳解Python自定義容器的完全指南

    從基礎(chǔ)到高級詳解Python自定義容器的完全指南

    在Python編程中,容器是我們?nèi)粘i_發(fā)中最常接觸的數(shù)據(jù)結(jié)構(gòu)之一,掌握自定義容器技術(shù)不僅能提升代碼的??可復(fù)用性??和??可維護(hù)性??,還能幫助我們構(gòu)建更加??領(lǐng)域特定??的數(shù)據(jù)結(jié)構(gòu),下面就跟隨小編一起深入了解下吧
    2025-10-10
  • 利用python獲取當(dāng)前日期前后N天或N月日期的方法示例

    利用python獲取當(dāng)前日期前后N天或N月日期的方法示例

    最近在工作中遇到一個(gè)需求,查找資料發(fā)現(xiàn)了一個(gè)很好的時(shí)間組件,所以下面這篇文章主要給大家介紹了關(guān)于利用python獲取當(dāng)前日期前后N天或N月日期的方法示例,需要的朋友們可以參考借鑒,下面來一起看看吧。
    2017-07-07
  • 關(guān)于 Python opencv 使用中的 ValueError: too many values to unpack

    關(guān)于 Python opencv 使用中的 ValueError: too many values to unpack

    這篇文章主要介紹了關(guān)于 Python opencv 使用中的 ValueError: too many values to unpack,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2019-06-06
  • python求解漢諾塔游戲

    python求解漢諾塔游戲

    這篇文章主要為大家詳細(xì)介紹了python求解漢諾塔游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-07-07

最新評論

红原县| 当雄县| 马山县| 新干县| 和顺县| 高淳县| 长泰县| 湘乡市| 东乌珠穆沁旗| 忻城县| 上饶市| 东海县| 玛沁县| 潜江市| 东乌| 镇康县| 渑池县| 玛曲县| 南召县| 酒泉市| 焦作市| 河北省| 彭州市| 类乌齐县| 惠来县| 德保县| 璧山县| 团风县| 菏泽市| 沁阳市| 桐城市| 宁化县| 濉溪县| 乌兰县| 陇西县| 永福县| 德化县| 互助| 屯留县| 尼玛县| 铁岭市|