问题描述
我试图从基类继承一个变量,但是解释器抛出错误.
I am trying to inherit a variable from base class but the interpreter throws an error.
这是我的代码:
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()
这是输出:
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'
代码有什么问题?
推荐答案
访问它之前,您需要定义 self.urllib_data
.最简单的方法是在初始化期间创建它,例如
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
这样,您可以确保每次尝试访问它时都存在.从您的代码中,我认为您不想在初始化期间获取实际数据.或者,您可以从 __ init __(..)
调用 self.url_lib()
来首次读取数据.稍后将以与以前相同的方式进行更新.
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.
这篇关于使用继承访问类外的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!