【问题标题】:Dealing with returns of different types of methods in oop在oop中处理不同类型方法的返回
【发布时间】:2018-09-04 13:44:41
【问题描述】:

我正在通过 TheGuardian.search_content()TheGuardian.data_to_csv() 方法使用 Guardian Python API。第一个返回一个字典,称为json_content。第二个,遍历 json_content 并将其内容写入 CSV 文件。我的问题是,为什么TheGuardian.data_to_csv() 方法接收<class 'script_guardian.TheGuardian'> 而不是<class 'dict'>

如果我理解正确的话,TheGuardian.data_to_csv() 只是接收到 TheGuardian 类的一个实例。这与我使用的方法类型有关吗?例如,抽象、静态或类方法

步骤:

>>> from script_guardian import TheGuardian
>>> tg = TheGuardian('2016-01-01', '2018-01-01')
>>> json_content = tg.search_content('education', 'relevance', 'education')
>>> json_content
<bound method Content.get_content_response of <theguardian.theguardian_content.Content object at 0x7f7bb9764c88>>
>>> type(json_content)
<class 'method'>

我怎样才能得到 search_content 的返回而不是方法本身?

我的完整代码:

import requests
from theguardian import theguardian_content
import csv

    class TheGuardian:

        def __init__(self, from_date='2016-01-01', to_date='2018-01-01'):
            self.from_date = from_date
            self.to_date = to_date

        def search_content(self, content='education', page_size=10, order_by='relevance', 
            api_key='test'):

            self.content = content
            self.page_size = page_size
            self.order_by = order_by
            self.api_key = api_key

            # create content
            params = {
                'from-date': self.from_date,
                'to_date': self.to_date,
                'order-by': self.order_by,
                'page-size': self.page_size,
                'q': self.content,
                'api': self.api_key
            }

            # create content
            content = theguardian_content.Content(**params)
            pdb.set_trace()
            json_content = content.get_content_response()

            # actual response
            return json_content

        def data_to_csv(self, json_content):

           self.json_content = json_content

            with open('guardian_data.csv','w') as csv_file:
                writer = csv.writer(csv_file, delimiter=',')
                writer.writerow(["webUrl", "webPublicationDate", "webTitle", "sectionName", 
                "apiUrl", "id", "isHosted", "sectionId", "type", "pillarId", "pillarName"])


                for result in json_content['response']['results']:
                    writer.writerow(
                        result["webUrl"],
                        result["webPublicationDate"],
                        result["webTitle"],
                        result["sectionName"],
                        result["apiUrl"],
                        result["id"],
                        result["isHosted"],
                        result["sectionId"],
                        result["type"],
                        result["pillarId"],
                        result["pillarName"]
                    )

【问题讨论】:

    标签: python-3.x api oop methods


    【解决方案1】:

    您的data_to_csv 不完整,因为您将其作为类方法访问。您应该将其定义为data_to_csv(self,json_content) 并将搜索内容的结果传递给它,例如tg.data_to_csv(tg.search_content())

    好好看看这个文档页面,https://docs.python.org/2/tutorial/classes.html

    【讨论】:

    • 为什么我不能简单地运行:json_content = tg.search_content('education', 'relevance', 'education') 然后 tg.data_to_csv(json_content)?这样做,我得到 TypeError: 'method' object is not subscriptable
    • 您仍然必须在 TheGuardian 类中为 data_to_csv 进行更改。只要您使用类方法,第一个参数就保留用于对类对象的引用。上面链接的文档清楚地解释了它。如果你定义了data_to_csv to be -&gt; data_to_csv(self,json_content)
    • 即使这样做,我得到的是方法本身,而不是 search_content 返回的字典。看起来我没有在 json_content = tg.search_content('education', 'relevance', 'education') 中调用 search_content
    • &gt;&gt;&gt; type(tg.search_content('education', 'relevance', 'education')) =&gt; &lt;class 'dict'&gt; 这是我运行代码时得到的。
    • 从您的代码中删除 pdb.set_trace,这是导致问题的原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-11
    • 2016-03-19
    • 2022-11-15
    • 1970-01-01
    相关资源
    最近更新 更多