【问题标题】:OOP PYTHON: Using cls() to create multiple constructor without calling __init__ [duplicate]OOP PYTHON:使用 cls() 创建多个构造函数而不调用 __init__ [重复]
【发布时间】: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


【解决方案1】:

一个简单的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']

【讨论】:

  • 我按照你说的做了,我还在一个名为 from_crawled 的类方法中将我的爬虫从初始化中取出。 if 语句将根据 init 中的参数调用 from_crawled 或 from_elasticsearch。这是一个好的架构吗?我应该使用@classmethod 吗?
  • 听起来不错。类方法的使用看起来也很合理。
  • 您推荐哪种方式:仅使用我的 init 方法来定义我的属性的类型并使用类方法来创建我的对象或在我的 init 中放置一个 if 语句,添加方法和来自 Elasticsearch 的响应作为参数?
  • 我允许在不需要类方法的情况下制作完全工作的实例。所以__init__ 中的 if 似乎没问题。
猜你喜欢
  • 2018-10-02
  • 2013-09-24
  • 2017-08-25
  • 2012-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-17
相关资源
最近更新 更多