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

2024-06-05 23:36:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将get\img\u url的方法属性local\u filename传递给ImgurDownload,但出现了错误

"AttributeError: ImgurDownload instance has no attribute '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()

Tags: imageimportselfcomurltargetgetif
2条回答

什么时候self.local\u文件名变量是在download\u image()方法中访问的。python将检查本地\u filename实例变量。但是,由于在下载\ u image()中访问该变量之前,该变量没有设置为实例变量,因此python将抛出AttributeError。你知道吗

我们必须确保这个变量在访问它之前被实例化。最好的方法是在init中实例化它。然后,在下载\u image()时,它会在self中附加一个初始化的本地\u filename变量。你知道吗

self.local_filename仅当a)首先调用get_img_url并且b)链接包含imgur.com. 在您的示例中,您还没有完成一项任务。你知道吗

相关问题 更多 >