Python:这遵循哪种编程范式?
在过去的两天里,我一直在研究装饰器,以及它们是如何轻松地创建和修改类的。这次探索让我写出了这段代码。
Factory.py
#!/usr/bin/env python
import sys
import functools
class Factory(object):
def with_callback(self, func):
postname = func.func_name
def wraped(callback, *args, **kw):
cbname = callback.func_name
print 'Passing {post} to {cb}'.format(post=postname, cb=cbname)
premute = func(*args, **kw)
return callback(premute)
return wraped
def __str__(self):
return str(self.__dict__)
def register(self, name):
def func_wrapper(func):
self.__dict__[name] = func
return func
return func_wrapper
def __getitem__(self, name):
return self.__dict__.get(name, None)
def __setitem__(self, name):
self.register(name)
def __call__(self, name=None, *args, **kw):
return self.__dict__.get(name, None)(*args, **kw)
def copy(self, old):
class DerivedFactory(self.__class__):
def __init__(self):
self.__dict__ = old.__dict__
self.__class__ = old.__class__
return DerivedFactory()
if __name__ == '__main__':
import requests
app = Factory()
@app.register('process_response')
def process_response(response):
print response.content
@app.register('get')
@app.with_callback
def get(url):
return requests.get(url)
x = app('get', app.process_response, 'http://www.google.com')
print x
这是 Factory.py 的一个示例用法
#!/usr/bin/env python
import Factory
import requests
from bs4 import BeautifulSoup as bs
class App(Factory.Factory):
pass
Parser = App()
@Parser.register('get_soup')
@Parser.with_callback
def _get(url, *req_args, **req_kw):
response = requests.get(url, *req_args, **req_kw)
return bs(response.content)
@Parser.register('get_links')
def _getlinks(soup):
return soup.find_all('', {'href':True})
print Parser('get_soup', Parser.get_links, 'http://www.google.com')
编程有六种主要的范式:
- 命令式
- 声明式
- 函数式
- 面向对象
- 逻辑式
- 符号式
哪一种范式最能描述 Factory.py 呢?
1 个回答
2
这些设计模式(四人帮的设计模式)几乎都是面向对象的,而工厂模式则是一种函数。虽然在函数式编程和逻辑编程中也有设计模式,但大多数都不太一样。
而且,你不能说真的有六种编程范式。很多范式之间其实是有重叠的,比如面向对象的编程几乎总是和命令式编程有关联。
最后,设计模式并不完全依赖于这些范式。范式是一些思维工具,用来引导计算能力的使用。而设计模式只是为这些范式发展出来的最佳实践。其实并没有什么理论基础说明责任链模式比一些奇怪的混乱代码更有效……