python - 如何在其他方法中使用 "_init_ "的参数?

标签 python init

我想在我的 _init_ 方法中使用一个参数 'term'。如您所见,当 _init 方法获取此参数时,我想将其用作我的数据库集合的名称并将数据插入其中。但是我不知道如何在整个类中使用 _init 中的 term 的值。那么有人对我有什么好的建议来处理这个问题吗?

class EPGDspider(scrapy.Spider):
        name = "EPGD"
        allowed_domains = ["epgd.biosino.org"]

    db = DB_Con()
    collection = db.getcollection(term)

    def __init__(self, term=None, *args, **kwargs):
        super(EPGDspider, self).__init__(*args, **kwargs)
        self.start_urls = ['http://epgd.biosino.org/EPGD/search/textsearch.jsp?textquery=%s&submit=Feeling+Lucky' % term]

    def parse(self, response):
        sel = Selector(response)
        sites = sel.xpath('//tr[@class="odd"]|//tr[@class="even"]')
        url_list = []
        base_url = "http://epgd.biosino.org/EPGD"

        for site in sites:
            item = EPGD()
            item['description'] = map(unicode.strip, site.xpath('td[6]/text()').extract())
            self.collection.update({"genID": item['genID']}, dict(item), upsert=True)
            yield item

最佳答案

让它成为 instance variable :

def __init__(self, term=None, *args, **kwargs):
    super(EPGDspider, self).__init__(*args, **kwargs)

    self.term = term
    # ...

然后,在其他方法中使用self.term引用它:

def parse(self, response):
    print(self.term)
    # ...

关于python - 如何在其他方法中使用 "_init_ "的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36758719/

相关文章:

android - 在 init.rc 中测试属性是否未设置

objective-c - 在 Objective-C 中,我为什么要检查 self = [super init] 是否不为零?

python - Lightgbm 排名示例

python - Pytube Python错误: download() missing 1 required positional argument: “tmp_path”

ios - initWithNibName 不实现父类(super class) - Swift

android boot - 在 init.c 中读取的 init.%hardware%.rc 在哪里?服务从哪里开始?

linux - InitScript Debian Insserv 未在启动时启动

Python 循环不工作 (xlwt)

python - 检查 NumPy 数组是否在 Python 列表中

python - Qt.QueuedConnection 从不发送消息