【发布时间】:2017-07-01 07:36:38
【问题描述】:
我有一个 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方法吗?
【问题讨论】:
-
所以你想创建一个对象而不初始化一个对象?
-
也许你的
__init__中不应该有那些爬虫的东西。 -
@StevenSummers 我想要两个知道我是否可以有 2 个不同的构造函数
-
不,
python不支持重载方法。但是,它确实允许您提供可选参数,并且您可以传递一个标志 (bool) 来确定其他操作。或者使用其他方法设置值。或者正如 khelwood 所提到的,重新构建您的代码,以便在您调用它时运行它。
标签: python python-3.x class oop instantiation