OOP PYTHON:使用cls()创建多个构造函数而无需调用__init__

梅尔

我有一个Python类,该类接受参数中的url并在新闻网站上启动搜寻器。

对象创建完成后,该对象将存储在Elasticsearch集群中。

我想创建一个方法,该方法接受Elasticsearch文档的输入,并从中创建一个对象。

class NewsArticle():

    def __init__(self, url):
        self.url = url
        # Launch a crawler and fill in the other fields like author, date, ect ...

    @classmethod
    def from_elasticsearch(cls, elasticsearch_article):
        document = elasticsearch_article['_source']
        obj = cls(document['url'])
        obj.url = document['url']
        obj.author = document['author']
        .
        .
        .

问题是,当我打电话时...

# response is my document from elasticsearch
res = NewsArticle.from_elasticsearch(response)

...该方法__init__将被调用并启动我的搜寻器。无论如何,它不会启动我的搜寻器或调用init方法吗?

迈克·米勒

简单if和默认参数如何crawl

class NewsArticle():

    def __init__(self, url, crawl=True):
        self.url = url
        if crawl:
            # Launch a crawler and fill in the other fields like author, date, ect ...

    @classmethod
    def from_elasticsearch(cls, elasticsearch_article):
        document = elasticsearch_article['_source']
        obj = cls(document['url'], crawl=False)
        obj.url = document['url']
        obj.author = document['author']

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章