7.9小节完成~
This commit is contained in:
33
cookbook/c07/p09_class_to_func.py
Normal file
33
cookbook/c07/p09_class_to_func.py
Normal file
@@ -0,0 +1,33 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- encoding: utf-8 -*-
|
||||
"""
|
||||
Topic: 单方法类转换为函数
|
||||
Desc :
|
||||
"""
|
||||
|
||||
from urllib.request import urlopen
|
||||
|
||||
|
||||
class 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 yahoo
|
||||
yahoo = 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 use
|
||||
yahoo = 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'))
|
||||
Reference in New Issue
Block a user