Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

python - Accessing variable outside class using inheritance

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...