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

python反射機(jī)制內(nèi)置函數(shù)及場景構(gòu)造詳解

 更新時間:2022年11月09日 10:24:58   作者:Silent丿丶黑羽  
這篇文章主要為大家介紹了python反射機(jī)制內(nèi)置函數(shù)及場景構(gòu)造示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

反射的優(yōu)點

它的核心本質(zhì)其實就是基于字符串的事件驅(qū)動,通過字符串的形式去操作對象的屬性或者方法

一個概念被提出來,就是要明白它的優(yōu)點有哪些,這樣我們才能知道為什么要使用反射。

場景構(gòu)造

開發(fā)1個網(wǎng)站,由兩個文件組成,一個是具體執(zhí)行操作的文件commons.py,一個是入口文件visit.py

需求:需要在入口文件中設(shè)置讓用戶輸入url, 根據(jù)用戶輸入的url去執(zhí)行相應(yīng)的操作

# commons.py
def login():
    print("這是一個登陸頁面!")
def logout():
    print("這是一個退出頁面!")
def home():
    print("這是網(wǎng)站主頁面!")
# visit.py
import commons
def run():
    inp = input("請輸入您想訪問頁面的url:  ").strip()
    if inp == 'login':
        commons.login()
    elif inp == 'logout':
        commons.logout()
    elif inp == 'index':
        commons.home()
    else:
        print('404')
if __name__ == '__main__':
    run()

運行run方法后,結(jié)果如下:

請輸入您想訪問頁面的url:  login
這是一個登陸頁面!

提問:上面使用if判斷,根據(jù)每一個url請求去執(zhí)行指定的函數(shù),若commons.py中有100個操作,再使用if判斷就不合適了回答:使用python反射機(jī)制,commons.py文件內(nèi)容不變,修改visit.py文件,內(nèi)容如下

import commons
def run():
    inp = input("請輸入您想訪問頁面的url:  ").strip()
    if hasattr(commons, inp):
        getattr(commons, inp)()
    else:
        print("404")
if __name__ == '__main__':
    run()

使用這幾行代碼,可以應(yīng)對commons.py文件中任意多個頁面函數(shù)的調(diào)用!

反射中的內(nèi)置函數(shù)

getattr

def getattr(object, name, default=None): # known special case of getattr
    """
    getattr(object, name[, default]) -> value
    Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
    When a default argument is given, it is returned when the attribute doesn't
    exist; without it, an exception is raised in that case.
    """
    pass

getattr()函數(shù)的第一個參數(shù)需要是個對象,上面的例子中,我導(dǎo)入了自定義的commons模塊,commons就是個對象;第二個參數(shù)是指定前面對象中的一個方法名稱。

getattr(x, 'y')等價于執(zhí)行了x.y。假如第二個參數(shù)輸入了前面對象中不存在的方法,該函數(shù)會拋出異常并退出。所以這個時候,為了程序的健壯性,我們需要先判斷一下該對象中有沒有這個方法,于是用到了hasattr()函數(shù)

hasattr

def hasattr(*args, **kwargs): # real signature unknown
    """
    Return whether the object has an attribute with the given name.
    This is done by calling getattr(obj, name) and catching AttributeError.
    """
    pass

hasattr()函數(shù)返回對象是否擁有指定名稱的屬性,簡單的說就是檢查在第一個參數(shù)的對象中,能否找到與第二參數(shù)名相同的方法。源碼的解釋還說,該函數(shù)的實現(xiàn)其實就是調(diào)用了getattr()函數(shù),只不過它捕獲了異常而已。所以通過這個函數(shù),我們可以先去判斷對象中有沒有這個方法,有則使用getattr()來獲取該方法。

setattr

def setattr(x, y, v): # real signature unknown; restored from __doc__
    """
    Sets the named attribute on the given object to the specified value.
    setattr(x, 'y', v) is equivalent to ``x.y = v''
    """
    pass

setattr()函數(shù)用來給指定對象中的方法重新賦值(將新的函數(shù)體/方法體賦值給指定的對象名)僅在本次程序運行的內(nèi)存中生效。setattr(x, 'y', v)等價于x.y = v

delattr

def delattr(x, y): # real signature unknown; restored from __doc__
    """
    Deletes the named attribute from the given object.
    delattr(x, 'y') is equivalent to ``del x.y''
    """
    pass

刪除指定對象中的指定方法,特別提示:只是在本次運行程序的內(nèi)存中將該方法刪除,并沒有影響到文件的內(nèi)容

__import__模塊反射

接著上面網(wǎng)站的例子,現(xiàn)在一個后臺文件已經(jīng)不能滿足我的需求,這個時候需要根據(jù)職能劃分后臺文件,現(xiàn)在我又新增了一個user.py這個用戶類的文件,也需要導(dǎo)入到首頁以備調(diào)用。

但是,上面網(wǎng)站的例子,我已經(jīng)寫死了只能指定commons模塊的方法任意調(diào)用,現(xiàn)在新增了user模塊,那此時我又要使用if判斷?

答:不用,使用Python自帶的函數(shù)__import__

由于模塊的導(dǎo)入也需要使用Python反射的特性,所以模塊名也要加入到url中,所以現(xiàn)在url請求變成了類似于commons/visit的形式

# user.py
def add_user():
    print('添加用戶')
def del_user():
    print('刪除用戶')
# commons.py
def login():
    print("這是一個登陸頁面!")
def logout():
    print("這是一個退出頁面!")
def home():
    print("這是網(wǎng)站主頁面!")
# visit.py
def run():
    inp = input("請輸入您想訪問頁面的url:  ").strip()
    # modules代表導(dǎo)入的模塊,func代表導(dǎo)入模塊里面的方法
    modules, func = inp.split('/')
    obj_module = __import__(modules)
    if hasattr(obj_module, func):
        getattr(obj_module, func)()
    else:
        print("404")
if __name__ == '__main__':
    run()

最后執(zhí)行run函數(shù),結(jié)果如下:

請輸入您想訪問頁面的url:  user/add_user
添加用戶
請輸入您想訪問頁面的url:  user/del_user
刪除用戶

現(xiàn)在我們就能體會到__import__的作用了,就是把字符串當(dāng)做模塊去導(dǎo)入。

但是如果我的網(wǎng)站結(jié)構(gòu)變成下面的

|- visit.py
|- commons.py
|- user.py
|- lib
    |- __init__.py
    |- connectdb.py

現(xiàn)在我想在visit頁面中調(diào)用lib包下connectdb模塊中的方法,還是用之前的方式調(diào)用可以嗎?

# connectdb.py
def conn():
    print("已連接mysql")
# visit.py
def run():
    inp = input("請輸入您想訪問頁面的url:  ").strip()
    # modules代表導(dǎo)入的模塊,func代表導(dǎo)入模塊里面的方法
    modules, func = inp.split('/')
    obj_module = __import__('lib.' + modules)
    if hasattr(obj_module, func):
        getattr(obj_module, func)()
    else:
        print("404")
if __name__ == '__main__':
    run()

運行run命令,結(jié)果如下:

請輸入您想訪問頁面的url:  connectdb/conn
404

結(jié)果顯示找不到,為了測試調(diào)用lib下的模塊,我拋棄了對所有同級目錄模塊的支持,所以我們需要查看__import__源碼

def __import__(name, globals=None, locals=None, fromlist=(), level=0): # real signature unknown; restored from __doc__
    """
    __import__(name, globals=None, locals=None, fromlist=(), level=0) -> module
    Import a module. Because this function is meant for use by the Python
    interpreter and not for general use, it is better to use
    importlib.import_module() to programmatically import a module.
    The globals argument is only used to determine the context;
    they are not modified.  The locals argument is unused.  The fromlist
    should be a list of names to emulate ``from name import ...'', or an
    empty list to emulate ``import name''.
    When importing a module from a package, note that __import__('A.B', ...)
    returns package A when fromlist is empty, but its submodule B when
    fromlist is not empty.  The level argument is used to determine whether to
    perform absolute or relative imports: 0 is absolute, while a positive number
    is the number of parent directories to search relative to the current module.
    """
    pass

__import__函數(shù)中有一個fromlist參數(shù),源碼解釋說,如果在一個包中導(dǎo)入一個模塊,這個參數(shù)如果為空,則return這個包對象,如果這個參數(shù)不為空,則返回包下面指定的模塊對象,所以我們上面是返回了包對象,所以會返回404的結(jié)果,現(xiàn)在修改如下:

# visit.py
def run():
    inp = input("請輸入您想訪問頁面的url:  ").strip()
    # modules代表導(dǎo)入的模塊,func代表導(dǎo)入模塊里面的方法
    modules, func = inp.split('/')
    # 只新增了fromlist=True
    obj_module = __import__('lib.' + modules, fromlist=True)
    if hasattr(obj_module, func):
        getattr(obj_module, func)()
    else:
        print("404")
if __name__ == '__main__':
    run()

運行run方法,結(jié)果如下:

請輸入您想訪問頁面的url:  connectdb/conn
已連接mysql

成功了,但是我寫死了lib前綴,相當(dāng)于拋棄了commonsuser兩個導(dǎo)入的功能,所以以上代碼并不完善,需求復(fù)雜后,還是需要對請求的url做一下判斷

def getf(module, func):
    """
    抽出公共部分
    """
    if hasattr(module, func):
        func = getattr(module, func)
        func()
    else:
        print('404')
def run():
    inp = input("請輸入您想訪問頁面的url:  ").strip()
    if len(inp.split('/')) == 2:
        # modules代表導(dǎo)入的模塊,func代表導(dǎo)入模塊里面的方法
        modules, func = inp.split('/')
        obj_module = __import__(modules)
        getf(obj_module, func)
    elif len(inp.split("/")) == 3:
        p, module, func = inp.split('/')
        obj_module = __import__(p + '.' + module, fromlist=True)
        getf(obj_module, func)
if __name__ == '__main__':
    run()

運行run函數(shù),結(jié)果如下:

請輸入您想訪問頁面的url:  lib/connectdb/conn
已連接mysql
請輸入您想訪問頁面的url:  user/add_user
添加用戶

當(dāng)然你也可以繼續(xù)優(yōu)化代碼,現(xiàn)在只判斷了有1個斜杠和2個斜杠的,如果目錄層級更多呢,這個暫時不考慮,本次是為了了解python的反射機(jī)制

以上就是python反射機(jī)制內(nèi)置函數(shù)及場景構(gòu)造詳解的詳細(xì)內(nèi)容,更多關(guān)于python反射機(jī)制內(nèi)置函數(shù)的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • python中format函數(shù)與round函數(shù)的區(qū)別

    python中format函數(shù)與round函數(shù)的區(qū)別

    大家好,本篇文章主要講的是python中format函數(shù)與round函數(shù)的區(qū)別,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下
    2022-01-01
  • Python調(diào)用百度AI實現(xiàn)圖片上表格識別功能

    Python調(diào)用百度AI實現(xiàn)圖片上表格識別功能

    這篇文章主要給大家介紹了關(guān)于Python調(diào)用百度AI實現(xiàn)圖片上表格識別功能的相關(guān)資料,在Python環(huán)境下,利用百度AI開放平臺文字識別技術(shù),對表格類圖片進(jìn)行識別,需要的朋友可以參考下
    2021-09-09
  • pytest中配置文件pytest.ini使用

    pytest中配置文件pytest.ini使用

    本文主要介紹了pytest中配置文件pytest.ini使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-05-05
  • django之對django內(nèi)置的User模型進(jìn)行自定義擴(kuò)展方式

    django之對django內(nèi)置的User模型進(jìn)行自定義擴(kuò)展方式

    這篇文章主要介紹了django之對django內(nèi)置的User模型進(jìn)行自定義擴(kuò)展方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-05-05
  • 用python批量移動文件

    用python批量移動文件

    這篇文章主要介紹了如何用python批量移動文件,幫助大家更好的理解和使用python,感興趣的朋友可以了解下
    2021-01-01
  • Request的中斷和ErrorHandler實例解析

    Request的中斷和ErrorHandler實例解析

    這篇文章主要介紹了Request的中斷和ErrorHandler實例解析,分享了相關(guān)代碼示例,小編覺得還是挺不錯的,具有一定借鑒價值,需要的朋友可以參考下
    2018-02-02
  • Python的Django框架中settings文件的部署建議

    Python的Django框架中settings文件的部署建議

    這篇文章主要介紹了Python的Django框架中settings文件的部署建議,包括對local_settings的弊病的一些簡單分析,需要的朋友可以參考下
    2015-05-05
  • 對python中Json與object轉(zhuǎn)化的方法詳解

    對python中Json與object轉(zhuǎn)化的方法詳解

    今天小編就為大家分享一篇對python中Json與object轉(zhuǎn)化的方法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-12-12
  • 詳解pytorch tensor和ndarray轉(zhuǎn)換相關(guān)總結(jié)

    詳解pytorch tensor和ndarray轉(zhuǎn)換相關(guān)總結(jié)

    這篇文章主要介紹了詳解pytorch tensor和ndarray轉(zhuǎn)換相關(guān)總結(jié),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-09-09
  • python實現(xiàn)將字符串中的數(shù)字提取出來然后求和

    python實現(xiàn)將字符串中的數(shù)字提取出來然后求和

    這篇文章主要介紹了python實現(xiàn)將字符串中的數(shù)字提取出來然后求和,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-04-04

最新評論

拜泉县| 达拉特旗| 京山县| 余干县| 米脂县| 昭觉县| 南丰县| 朝阳县| 凌源市| 云安县| 东丰县| 宾阳县| 金塔县| 天长市| 栾川县| 新营市| 淮滨县| 封丘县| 肃南| 冀州市| 德清县| 邓州市| 桂林市| 章丘市| 丰城市| 全椒县| 满洲里市| 平山县| 榆林市| 大港区| 密云县| 盐源县| 鹤山市| 崇仁县| 武安市| 呈贡县| 乌兰县| 阳新县| 保定市| 那坡县| 尉氏县|