通过一对简单的课程,我无法超级工作:
class A(object):
q = 'foo'
class B(A):
q = 'bar'
def __init__(self):
self.a = super(A, self).q
a = B()
像这样的错误:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-210-802575054d17> in <module>()
5 def __init__(self):
6 self.a = super(A, self).q
----> 7 a = B()
<ipython-input-210-802575054d17> in __init__(self)
4 q = 'bar'
5 def __init__(self):
----> 6 self.a = super(A, self).q
7 a = B()
AttributeError: 'super' object has no attribute 'q'
我在堆栈交换,阅读文档和文章方面看到了类似的问题,并且所有帐户都应该有效。我错过了什么明显的事情?
编辑:答案是我引用了错误的类,并修复它修复了示例,但不是我的真实代码,如下所示:
class D(object):
pwd = ['~/']
def __init__(self,*args):
if len(args) == 1:
self.cd(args[0])
else:
return
def __str__(self):
if len(self.pwd) == 1:
return self.pwd[0]
else:
return ''.join(self.pwd)
def __add__(self,other):
if type(other) is str:
return str(self) + other
elif type(other) is list:
return pwd + other
def cd(self, directory):
#import pdb; pdb.set_trace()
reset = False
if directory[0] is '~':
reset = True
if directory[0] is '/':
reset = True
directory = directory[1:]
if directory[-1] is '/':
directory = directory[:-1]
directory = [folder+'/' for folder in directory.split('/')]
rverse = directory.count('../')
if rverse > 0 and type(directory) is list:
end = False
for folder in directory:
if folder == '../' and end:
raise Exception('improperly placed ".."')
if folder != '../':
end = True
if reset:
self.pwd = directory
else:
self.pwd = self.pwd + directory
print self
class Dirchanger(D):
def __init__(self,client,*args):
if len(args) == 1:
self.cd(args[0])
def cd(self,directory):
super(D, self).cd(directory)
显然,该代码不完整,但它应该基于答案。
答案 0 :(得分:4)
您正在使用错误的搜索目标(第一个参数);改为使用super(B, self)
:
def __init__(self):
self.a = super(B, self).q
第一个参数给出super()
一个起点;它意味着通过MRO查看,从我给你的那个下一个类开始,其中MRO是 second 参数的方法解析顺序({{1} })。
通过告诉type(self).__mro__
开始查看 super()
,您有效地告诉A
在MRO太远的地方开始搜索。接下来是super()
,该类型 具有object
属性:
q
您的真实代码有完全相同的问题:
>>> B.__mro__
(<class '__main__.B'>, <class '__main__.A'>, <type 'object'>)
您正在class Dirchanger(D):
def __init__(self,client,*args):
if len(args) == 1:
self.cd(args[0])
def cd(self,directory):
super(D, self).cd(directory)
开始MRO搜索,而不是D
此处。