【发布时间】:2019-09-07 04:54:43
【问题描述】:
这里是 Python 初学者。假设我有三种抓取网站的方法。我们称它们为scrape_site_a、scrape_site_b 和scrape_site_c。我想运行其中的每一个,但我想以这样一种方式定义它们,即我可以动态地调用它们而无需通过名称调用它们。理想情况下,我只想将所有模块加载到一个目录中并在每个模块上调用相同的方法。到目前为止,我的尝试如下:
site_a.py
def scrape():
# scrape the site
site_b.py
def scrape():
# scrape the site
site_c.py
def scrape():
# scrape the site
我有__init__.py 设置,因此我可以执行以下操作:
scrape.py
from sites import *
site_a.scrape()
site_b.scrape()
site_c.scrape()
我想做这样的事情:
for site in sites:
site.scrape()
我意识到这里有一个我不理解的基本编程概念,我有两个问题:
- 有没有办法使用我正在采取的方法来做到这一点?
- 有更好的方法吗?为什么?
【问题讨论】:
-
使用类作为名称板而不是模块。
-
您正在寻找的是类似于 OSGi 的东西(但它的框架太大,无法一次性解释)。
标签: python design-patterns architecture