我想用兩種方法構建一個類:第一種方法檢查文件是否無錯地下載,第二種方法是保存下載的文件。此代碼按我的需要工作,但它將文件下載兩次。我想在第二種方法中使用第一種方法的r
變量而不再次下載文件。python 3.在同一類中使用另一種方法中的變量
發送電子郵件的功能工作得很好。
from collections import OrderedDict
import requests
class checkGet_and_loads:
# check if the get is successfull or not
def get(self, url, file):
# download the file
self.r = requests.get(url)
# check if file was downloaded with no errors
if self.r.status_code != 200:
# send email to gmail
# emailBody = 'Sending email. Error with downloading the ' + file + ' file.'
# send_email(fromaddr = emailFrom, pwd = password, toaddr = emailTo, Subject = emailSubject, body = emailBody)
print('Error: Unexpected response {}'.format(self.r))
else:
print(' Not sending email. No errors found when downloading the ' + file + ' file.')
# loads the json file
def loads(self, url, file):
# download the file
self.r = requests.get(url)
# loads the json file
self.to_loads = json.loads(self.r.text, object_pairs_hook = OrderedDict)
return(self.to_loads)
# Check if test file is downloaded without errors. If errors found while downloading then send email; otherwise, don't email
# link for test file
url = 'http://mysafeinfo.com/api/data?list=englishmonarchs&format=json'
file = 'test'
checkGet_and_loads().get(url, file)
test_json = checkGet_and_loads().loads(url, file)
所以第二個方法應該是這樣的:
# loads the json file
def loads(self):
# loads the json file
to_loads = json.loads(self.r.text, object_pairs_hook = OrderedDict)
return(to_loads)
但是,我得到這個錯誤:
AttributeError: 'checkGet_and_loads' object has no attribute 'r'
我試着SO和其他網站所有的解決方案,並沒有找出它...
它的工作原理。謝謝。 有點編輯:它應該是'test_json = data_source.loads()'而不是'test_json = data_source.loads(url,file)' – nick
@nick當然。固定。 – m0nhawk