动态添加属性

  1. class Article(object):
  2. def __init__(self, **kwargs):
  3. for k, v in kwargs.items():
  4. setattr(self, k, v)
  5. article = Article(pmid='1', title='hello world')
  6. article.pmid # '1'
  7. article.title # 'hellow world'

动态添加方法

functools.partialmethod 需要Python3.4+

  1. import functools
  2. class Request(object):
  3. def __init__(self):
  4. print('>>> init ...')
  5. def func(self, method, url):
  6. print('>>> {} for url: {}'.format(method.upper(), url))
  7. for method in ['get', 'post', 'put', 'delete', 'head']:
  8. setattr(Request, method, functools.partialmethod(func, method))

or

  1. import functools
  2. def url_handler(self, method, url):
  3. print('>>> {} for url: {}'.format(method.upper(), url))
  4. class Request(object):
  5. """dynamically add request method
  6. examples:
  7. --------
  8. >>> r = Request()
  9. >>> r.get('www.baidu.com')
  10. """
  11. methods = ['get', 'post', 'put', 'delete', 'head']
  12. def __init__(self):
  13. for method in self.methods:
  14. setattr(Request, method, functools.partialmethod(url_handler, method))
  15. r = Request()
  16. help(r)
  17. r.get('www.baidu.com')
  18. r.delete('www.baidu.com')

image.png