Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to inherit a variable from base class but the interpreter throws an error.

Here is my code:

class LibAccess(object):
    def __init__(self,url):
        self.url = url

    def url_lib(self):
        self.urllib_data = urllib.request.urlopen(self.url).read()
        return self.urllib_data

class Spidering(LibAccess):
    def category1(self):
        print (self.urllib_data)


scrap = Spidering("http://jabong.com")
scrap.category1()

This is the output:

Traceback (most recent call last):
  File "variable_concat.py", line 16, in <module>
    scrap.category1()
  File "variable_concat.py", line 12, in category1
    print (self.urllib_data)
AttributeError: 'Spidering' object has no attribute 'urllib_data'

What is the problem with the code?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
276 views
Welcome To Ask or Share your Answers For Others

1 Answer

You will need to define self.urllib_data prior to accessing it. The simples way would be to create it during initialization, e.g.

class LibAccess(object):
    def __init__(self,url):
        self.url = url
        self.urllib_data = None

That way you can make sure it exists everytime you try to access it. From your code I take it that you do not want to obtain the actual data during initialization. Alternatively, you could call self.url_lib() from __init__(..) to read the data for the first time. Updating it later on would be done in the same way as before.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...