实例在将其传递给实例方法时没有属性

时间:2014-08-03 17:28:55

标签: python

我正在尝试将get_img_url的方法属性local_filename传递给ImgurDownload但是收到错误

"AttributeError: ImgurDownload instance has no attribute 'local_filename'"

是否可以在全局范围内使local_filename可用,以便其他方法可以访问它?

import re, os, glob, sys
import requests
from bs4 import BeautifulSoup
import pdb
import pprint

# imgur url pattern
imgurUrlPattern = re.compile(r'(http://i.imgur.com/(.*))(\?.*)?')


class ImgurDownload():

    #local_filename = None

    def __init__(self, link_url, target_subreddit, submissionid):
        self.link_url = link_url
        self.target_subreddit = target_subreddit
        self.submissionid = submissionid



    def download_image(self):
        response = requests.get("{}".format(self.link_url))
        if response.status_code == 200:
            #pdb.set_trace()

            #------------->2. local_filename is what i want to get from get_img_url <------------
            print('Downloading %s...' % self.local_filename)
            with open(self.local_filename, 'wb') as fo:
                for chunk in response.iter_content(4096):
                    fo.write(chunk)

    def get_img_url(self):

        if "imgur.com/" not in self.link_url:
            pass # skip non-imgur submissions

        if len(glob.glob('reddit_%s_%s_*' % (self.target_subreddit, self.submissionid))) > 0:
            pass # we've already downloaded files for this reddit submission

        if 'http://i.imgur.com/' in self.link_url:
            # The URL is a direct link to the image.
            mo = imgurUrlPattern.search(self.link_url) # using regex here instead of BeautifulSoup because we are pasing a url, not html

            imgurFilename = mo.group(2)
            if '?' in imgurFilename:
                # The regex doesn't catch a "?" at the end of the filename, so we remove it here.
                self.imgurFilename = imgurFilename[:imgurFilename.find('?')]

            #--------------------> 1. I want this instance var to be passed on to ^ download_image method <~-----------------------
            self.local_filename = 'reddit_%s_%s_album_None_imgur_%s' % (self.target_subreddit, self.submissionid, imgurFilename)
            self.download_image()

    def print_self_dict(self):
        pprint.pprint(self.__dict__)




sample = "http://i.imgur.com/yhemck6.jpg"
x = ImgurDownload('http://i.imgur.com/C5uIWlD.jpg','brogress','2cgwwn')
print x.download_image()
#x.print_self_dict()

2 个答案:

答案 0 :(得分:0)

self.local_filename仅在以下情况下定义:a)您先拨打get_img_url ,然后b)该链接包含imgur.com。在您的示例中,您还没有完成a)。

答案 1 :(得分:0)

当在download_image()方法中访问self.local_filename变量时,python将检查local_filename实例变量。但是因为在download_image()中访问它之前没有将该变量设置为实例变量,所以python会抛出一个AttributeError。

我们确保在访问它之前实例化该变量。最好的方法是在 init ()中实例化它。然后说到download_image(),它有一个初始化的local_filename变量附加到self。