python 3.在同一个类中的另一个方法中使用一个方法的变量

时间:2017-04-30 19:35:33

标签: json python-3.x class methods

我试图用两种方法构建一个类:第一种方法检查文件是否没有错误地下载,第二种方法是保存下载的文件。这段代码按我的意思运行,但它下载文件两次。我想在第二种方法中使用第一种方法的r变量而不再重新下载文件。

发送电子邮件的功能很好。

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:&#39; checkGet_and_loads&#39;对象没有属性&#39; <&#39;

我在SO和其他网站上尝试了所有解决方案,并没有弄明白......

2 个答案:

答案 0 :(得分:1)

因为您正在创建一个临时对象,然后创建一个新对象:

checkGet_and_loads().get(url, file)
test_json = checkGet_and_loads().loads(url, file)

应该是这样的:

data_source = checkGet_and_loads()
data_source.get(url, file)
test_json = data_source.loads()

然后您不需要在requests.get功能中拨打.loads

答案 1 :(得分:1)

我认为你所需要的东西可以简单得多。如果您的课程中只有两种方法,其中一种方法__init__,那么它应该是function。在你的情况下,你甚至没有init。

def load_file(url, filename):
    response = r.get(url)
    if response.status == 200:
        with open(filename, 'w') as f:
            json.dump(f, response.json(object_pairs_hook=OrderedDict))

如果raise CustomException()不是status,您可以200然后抓住它并记录错误。

我还建议阅读python代码样式(PEP8)

相关问题