动态添加属性
class Article(object):
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
article = Article(pmid='1', title='hello world')
article.pmid # '1'
article.title # 'hellow world'
动态添加方法
functools.partialmethod
需要Python3.4+
import functools
class Request(object):
def __init__(self):
print('>>> init ...')
def func(self, method, url):
print('>>> {} for url: {}'.format(method.upper(), url))
for method in ['get', 'post', 'put', 'delete', 'head']:
setattr(Request, method, functools.partialmethod(func, method))
or
import functools
def url_handler(self, method, url):
print('>>> {} for url: {}'.format(method.upper(), url))
class Request(object):
"""dynamically add request method
examples:
--------
>>> r = Request()
>>> r.get('www.baidu.com')
"""
methods = ['get', 'post', 'put', 'delete', 'head']
def __init__(self):
for method in self.methods:
setattr(Request, method, functools.partialmethod(url_handler, method))
r = Request()
help(r)
r.get('www.baidu.com')
r.delete('www.baidu.com')