继承类未运行继承类的super().__ init()

时间:2018-08-17 04:24:48

标签: python scrapy

运行搜寻器时,返回错误 NameError: name 'db' is not defined

我怀疑这是因为未执行初始化,但是我不确定代码有什么问题?任何想法?超级语句看起来不错,我什至尝试了其他类似super(TopAnimePipeline, self).__init__()的方法。

代码:

import pymongo
from scrapy.conf import settings
from scrapy.exceptions import DropItem

class MongoDBPipeline(object):

    def __init__(self):
        connection = pymongo.MongoClient(
            settings['MONGODB_SERVER'],
            settings['MONGODB_PORT']
        )
        db = connection[settings['MONGODB_DB']]

    def process_item(self, item, spider):
        valid = True
        for data in item:
            if not data:
                valid = False
                raise DropItem("Missing {0}!".format(data))
        if valid:
            self.collection.insert(dict(item))

        return item

class SeasonalAnimePipeline(MongoDBPipeline):

    def __init__(self):
        super().__init__()
        self.collection = db[settings['MONGODB_COLLECTION'][0]]

class TopAnimePipeline(MongoDBPipeline):

    def __init__(self):
        super().__init__()
        self.collection = db[settings['MONGODB_COLLECTION'][1]]

1 个答案:

答案 0 :(得分:0)

我将您的代码修改为简化版本。这样,您就可以访问 db 变量。您可以以此为参考,然后编写代码。请检查以下示例。

class MongoDBPipeline(object):

    def __init__(self):
        connection = 'col'
        self.db = {'a': 1}

    def process_item(self, item, spider):
        valid = True
        return item

class SeasonalAnimePipeline(MongoDBPipeline):

    def __init__(self):
        super().__init__()
        self.collection = self.db

a = SeasonalAnimePipeline()
print(a.collection)