【发布时间】:2016-04-09 22:18:51
【问题描述】:
问题是如何以安全和可维护的方式在对象之间共享数据。
示例: 我已经构建了产生大量蜘蛛的scrapy 应用程序。虽然每个蜘蛛都连接到单独的管道对象,但我需要比较和排序不同管道之间的数据(例如,我需要按不同项目属性排序的输出:价格、日期等),所以我需要一些共享数据区域。这同样适用于蜘蛛本身(例如,我需要计算最大总请求数)。 第一个实现使用类变量在蜘蛛/管道和每个对象的实例变量之间共享数据。
class MyPipeline(object):
max_price = 0
def process_item(self, item, spider):
if item['price'] > max_price :
max_price = item['price']
(实际结构更复杂)然后我想到拥有一堆静态不是OOP,下一个解决方案是为每个类拥有私有类数据并用于存储值:
class MyPipelineData:
def __init__(self):
self.max_price = 0
class SpidersData:
def __init___(self, total_requests, pipeline_data):
self.total_requests = total_requests
self.pipeline_data = pipeline_data #the shared data between pipelines
class MyPipeline(object):
pipeline_data = None
def process_item(self, item, spider):
if _data is None:
_data = spider.data.pipeline_data #the shared data between pipelines
if item['price'] > _data.max_price :
_data.max_price = item['price']
class Spider(scrapy.spider):
def __init__(self, spider_data):
self._data = spider_data
# and the same object of SpiderData is passed to all spiders
现在我有一个在所有管道之间共享的数据实例(对于蜘蛛也是如此)。我通常对此是否正确?我应该在 python 中应用与在 C++ 中相同的 OOP 方法吗?
【问题讨论】:
标签: python oop design-patterns architecture