简体   繁体   中英

AttributeError: instance has no attribute

This seems to be a common error in Python, and I've found many instances of people asking about similar but spent the last (long amount of time) trying those solutions where they seemed applicable and have had no luck, so resorting to asking to find out what I'm missing.

I'm receiving AttributeError: WebHandler instance has no attribute 'search_str'

It seems to be this one particular method, any time I call any of the class variables set in ___init___ from this method I receive this error. I've extracted it to a test file as a simple function rather than a class method and it works fine, and I've tried re-indenting everything a few times to make sure it wasn't that, so I'm at a loss on this.

I'm using Python 2.7 and TextWrangler if either of these are helpful (TextWrangler hasn't given me any problems in 3 years like this, but figured anything should be included)

import requests
import re

class WebHandler():

    def ___init___(self):
        self.urllist = []
        self.search_str = re.compile(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', re.I|re.M)

    def set_urls(self, test, data):
        for line in test[11:]:
            if (("even" in line) or ("odd" in line)):
                match = re.search(self.search_str, line)
            self.urllist.append(match.group(0))

Another thing I tried, if I copy the attributes from ___init___ and simply make them local to set_urls() and call them without self that way it works properly and doesn't throw any errors, which is confusing me even more.

No idea what I'm missing. Thanks!

This that you have:

def ___init___(self):

Is not the same as this that gets called when an object is instantiated:

def __init__(self):

The difference is that you have three underscores on either side of init , while two are required.

Your init function has three underscores:

def ___init___(self):

It should have only two :

def __init__(self):

As it is written now, it is not being called when you create a new object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM