【发布时间】: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