【问题标题】:python 3. Use variable from one method in another method within the same classpython 3.在同一类中的另一个方法中使用一个方法中的变量
【发布时间】:2017-09-28 08:42:01
【问题描述】:

我正在尝试使用两种方法构建一个类:第一种方法是检查文件是否下载时没有错误,第二种方法是保存下载的文件。此代码按我的意愿工作,但它会下载文件两次。我想在第二种方法中使用第一种方法中的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: 'checkGet_and_loads' 对象没有属性 'r'

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

【问题讨论】:

    标签: json python-3.x class methods


    【解决方案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()
    

    那么你就不需要在.loads函数中调用requests.get了。

    【讨论】:

    • 它有效。谢谢。稍微修改一下:应该是 test_json = data_source.loads() 而不是 test_json = data_source.loads(url, file)
    • @nick 当然。固定。
    【解决方案2】:

    我认为你需要的可以更简单地实现。如果你有一个只有两个方法的类,其中一个是__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))
    

    如果status 不是200,你可以raise CustomException() 然后捕获它并记录错误。

    我也建议阅读python代码风格(PEP8)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-03
      • 1970-01-01
      相关资源
      最近更新 更多