關於python單方法的類

來源:互聯網
上載者:User

標籤:def   連結地址   id3   參考   pen   需要   highlight   cut   orm   

1、大部分情況下,你擁有一個單方法類的原因是需要儲存某些額外的狀態來給方法使用。

 

此種情況下可以使用閉包代替,參考

關於這個計數器閉包和類各有千秋吧,但如果不是但方法的類,使用閉包類比物件導向,那肯定是沒有使用類好,類不光是封裝了,還可以繼承,代碼結構也更清晰。

 

 

 

將單方法的類轉換為函數問題

你有一個除 __init__() 方法外只定義了一個方法的類。為了簡化代碼,你想將它轉換成一個函數。

解決方案

大多數情況下,可以使用閉包來將單個方法的類轉換成函數。 舉個例子,下面樣本中的類允許使用者根據某個模板方案來擷取到URL連結地址。

from urllib.request import urlopenclass UrlTemplate:    def __init__(self, template):        self.template = template    def open(self, **kwargs):        return urlopen(self.template.format_map(kwargs))# Example use. Download stock data from yahooyahoo = UrlTemplate(‘http://finance.yahoo.com/d/quotes.csv?s={names}&f={fields}‘)for line in yahoo.open(names=‘IBM,AAPL,FB‘, fields=‘sl1c1v‘):    print(line.decode(‘utf-8‘))

這個類可以被一個更簡單的函數來代替:

def urltemplate(template):    def opener(**kwargs):        return urlopen(template.format_map(kwargs))    return opener# Example useyahoo = urltemplate(‘http://finance.yahoo.com/d/quotes.csv?s={names}&f={fields}‘)for line in yahoo(names=‘IBM,AAPL,FB‘, fields=‘sl1c1v‘):    print(line.decode(‘utf-8‘))

關於python單方法的類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.