亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python __setattr__、 __getattr__、 __delattr__、__call__用法示例

 更新時(shí)間:2015年03月06日 09:32:50   投稿:junjie  
這篇文章主要介紹了Python __setattr__、 __getattr__、 __delattr__、__call__用法示例,本文分別對(duì)這幾個(gè)魔法方法做了講解,需要的朋友可以參考下

getattr

`getattr`函數(shù)屬于內(nèi)建函數(shù),可以通過(guò)函數(shù)名稱獲取

復(fù)制代碼 代碼如下:

value = obj.attribute
value = getattr(obj, "attribute")

使用`getattr`來(lái)實(shí)現(xiàn)工廠模式
復(fù)制代碼 代碼如下:

#一個(gè)模塊支持html、text、xml等格式的打印,根據(jù)傳入的formate參數(shù)的不同,調(diào)用不同的函數(shù)實(shí)現(xiàn)幾種格式的輸出

import statsout

def output(data, format="text"):                          
    output_function = getattr(statsout, "output_%s" %format)
    return output_function(data)

__call__

`__call__`方法用于實(shí)例自身的調(diào)用:

復(fù)制代碼 代碼如下:

class storage(dict):
    # __call__方法用于實(shí)例自身的調(diào)用
    #達(dá)到()調(diào)用的效果
    def __call__ (self, key):
         try:
             return self[key]
         except KeyError, k:
             return None

s = storage()
s['key'] = 'value'
print s(key) #調(diào)用__call__

__getattr__

從對(duì)象中讀取某個(gè)屬性時(shí),首先需要從self.__dicts__中搜索該屬性,再?gòu)腳_getattr__中查找。

復(fù)制代碼 代碼如下:

class A(object): 
    def __init__(self): 
        self.name = 'from __dicts__: zdy' 
 
    def __getattr__(self, item): 
        if item == 'name': 
            return 'from __getattr__: zdy' 
        elif item == 'age': 
            return 26 
 
a = A() 
print a.name # 從__dict__里獲得的 
print a.age # 從__getattr__獲得的

__setattr__

`__setattr__`函數(shù)是用來(lái)設(shè)置對(duì)象的屬性,通過(guò)object中的__setattr__函數(shù)來(lái)設(shè)置屬性:

復(fù)制代碼 代碼如下:

class A(object):
    def __setattr__(self, *args, **kwargs): 
        print 'call func set attr' 
        return object.__setattr__(self, *args, **kwargs)

__delattr__

`__delattr__`函數(shù)式用來(lái)刪除對(duì)象的屬性:

復(fù)制代碼 代碼如下:

class A(object):
    def __delattr__(self, *args, **kwargs): 
        print 'call func del attr' 
        return object.__delattr__(self, *args, **kwargs) 

例子

完整例子可以參考微博API:http://github.liaoxuefeng.com/sinaweibopy/

復(fù)制代碼 代碼如下:

class _Executable(object):

    def __init__(self, client, method, path):
        self._client = client
        self._method = method
        self._path = path
    #__call__函數(shù)實(shí)現(xiàn)_Executable函數(shù)對(duì)象為可調(diào)用的
    def __call__(self, **kw):
        method = _METHOD_MAP[self._method]
        if method==_HTTP_POST and 'pic' in kw:
            method = _HTTP_UPLOAD
        return _http_call('%s%s.json' % (self._client.api_url, self._path), method, self._client.access_token, **kw)

    def __str__(self):
        return '_Executable (%s %s)' % (self._method, self._path)

    __repr__ = __str__

class _Callable(object):

    def __init__(self, client, name):
        self._client = client
        self._name = name

    def __getattr__(self, attr):
        if attr=='get':
       #初始化_Executable對(duì)象,調(diào)用__init__函數(shù)
            return _Executable(self._client, 'GET', self._name)
        if attr=='post':
            return _Executable(self._client, 'POST', self._name)
        name = '%s/%s' % (self._name, attr)
        return _Callable(self._client, name)

    def __str__(self):
        return '_Callable (%s)' % self._name

    __repr__ = __str__

而在源碼中,存在下面代碼片段:

復(fù)制代碼 代碼如下:

class APIClient(object):
    '''
    API client using synchronized invocation.
    '''
    ...

    def __getattr__(self, attr):
        if '__' in attr:
            return getattr(self.get, attr)
        return _Callable(self, attr)

因此,加入我們初始化對(duì)象,并調(diào)用某函數(shù)如下:

復(fù)制代碼 代碼如下:

client = APIClient(...)
#會(huì)調(diào)用__getattr__函數(shù),從而調(diào)用__call__函數(shù)
client.something.get()

相關(guān)文章

  • 創(chuàng)建pycharm的自定義python模板方法

    創(chuàng)建pycharm的自定義python模板方法

    今天小編就為大家分享一篇?jiǎng)?chuàng)建pycharm的自定義python模板方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-05-05
  • Python數(shù)據(jù)可視化之Seaborn的使用詳解

    Python數(shù)據(jù)可視化之Seaborn的使用詳解

    Seaborn庫(kù)是python中基于matplotlib庫(kù)的可視化工具庫(kù),通過(guò)sns我們可以更方便地繪制出更美觀的圖表。本文將分享python基于Seaborn庫(kù)的一系列繪圖操作,感興趣的可以了解一下
    2022-04-04
  • Python實(shí)現(xiàn)按學(xué)生年齡排序的實(shí)際問(wèn)題詳解

    Python實(shí)現(xiàn)按學(xué)生年齡排序的實(shí)際問(wèn)題詳解

    這篇文章主要給大家介紹了關(guān)于Python實(shí)現(xiàn)按學(xué)生年齡排序?qū)嶋H問(wèn)題的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面跟著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。
    2017-08-08
  • Python繪制的二項(xiàng)分布概率圖示例

    Python繪制的二項(xiàng)分布概率圖示例

    這篇文章主要介紹了Python繪制的二項(xiàng)分布概率圖,涉及Python基于numpy、math的數(shù)值運(yùn)算及matplotlib圖形繪制相關(guān)操作技巧,需要的朋友可以參考下
    2018-08-08
  • 淺談django model postgres的json字段編碼問(wèn)題

    淺談django model postgres的json字段編碼問(wèn)題

    下面小編就為大家分享一篇淺談django model postgres的json字段編碼問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-01-01
  • 詳解python文件的操作和異常的處理

    詳解python文件的操作和異常的處理

    這篇文章主要為大家介紹了python文件的操作和異常的處理,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助
    2021-12-12
  • Python進(jìn)程Multiprocessing模塊原理解析

    Python進(jìn)程Multiprocessing模塊原理解析

    這篇文章主要介紹了Python進(jìn)程Multiprocessing模塊原理解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-02-02
  • Python Sql數(shù)據(jù)庫(kù)增刪改查操作簡(jiǎn)單封裝

    Python Sql數(shù)據(jù)庫(kù)增刪改查操作簡(jiǎn)單封裝

    這篇文章主要為大家介紹了Python Sql數(shù)據(jù)庫(kù)增刪改查操作簡(jiǎn)單封裝,感興趣的小伙伴們可以參考一下
    2016-04-04
  • Python+matplotlib繪制餅圖和堆疊圖

    Python+matplotlib繪制餅圖和堆疊圖

    Matplotlib是Python的繪圖庫(kù),它能讓使用者很輕松地將數(shù)據(jù)圖形化,并且提供多樣化的輸出格式。本文將為大家介紹如何用matplotlib繪制餅圖和堆疊圖,感興趣的朋友可以學(xué)習(xí)一下
    2022-04-04
  • Python中的NumPy實(shí)用函數(shù)整理之percentile詳解

    Python中的NumPy實(shí)用函數(shù)整理之percentile詳解

    這篇文章主要介紹了Python中的NumPy實(shí)用函數(shù)整理之percentile詳解,NumPy函數(shù)percentile()用于計(jì)算指定維度上數(shù)組元素的第?n?個(gè)百分位數(shù),返回值為標(biāo)量或者數(shù)組,需要的朋友可以參考下
    2023-09-09

最新評(píng)論