我正在运行Windows 7,使用python 2.7.3,我得到一个继承错误,我无法弄清楚为什么。我已经做了很多搜索,但还没有找到太多关联。
我的问题是,当我尝试从一个类继承到另一个类时,我一直收到一个AttributeError。我的基本结构是这样的:
# pymyClass.py
class myClass(object):
def __init__(self,aList=None):
if aList is not None:
myList = aList
else:
myList = ['','','','','']
def reset(self,aList=None):
if aList is not None:
myList = aList
else:
myList = ['','','','','']
#other methods operate without issue
# pymySecondClass.py
import pymyClass
class mySecondClass(pymyClass.myClass):
def __init__(self,aList=None):
pymyClass.myClass(aList)
# pymyThirdClass.py
import pymySecondClass
class myThirdClass(pymySecondClass.mySecondClass):
def __init__(self,aList=None):
pymySecondClass.mySecondClass(aList)
def useList(self,aList=None):
self.reset(aList)
print self.myList
#pymyObj.py
import pymyThirdClass
myObj = pymyThirdClass.myThirdClass(['a','b','c','1','2'])
myObj.useList()
...但是当我调用myThirdClass()并调用useList()时,它出错了,说,
AttributeError: 'myThirdClass' object has no attribute 'myList'
我实际上在这里编译了我的例子,并得到了同样的问题,所以我认为继承不能按照我期望的方式工作。我已经检查了python文档,但可能还不够近?如果有人能帮助我,我将非常感激。
我想我可能只需要在myThirdClass构造函数中手动包含字段“myList”,但这看起来非常蹩脚。提前谢谢!
答案 0 :(得分:4)
您永远不会在任何地方将myList
实际附加到实例。要做到这一点(在方法内),你需要做:
self.myList = ...
而不仅仅是:
myList = ...
其中self
是传递给方法的第一个参数的常规名称。
您在派生类上调用基类的问题也存在一些问题。
class Foo(object):
def __init__(self):
print "I'm a Foo"
class Bar(Foo):
def __init__(self):
print "I'm a Bar"
#This is one way to call a method with the same name on a base class
Foo.__init__(self)
有些人不喜欢Foo.__init__(self)
- 这些人使用super
(which is Ok too作为long as you know what you're doing)。
答案 1 :(得分:2)
你忘记了自我:
# pymyClass.py
class myClass(object):
def __init__(self,aList=None):
if aList is not None:
self.myList = aList
else:
self.myList = ['','','','','']
def reset(self,aList=None):
if aList is not None:
self.myList = aList
else:
self.myList = ['','','','','']
没有这个mylist的在if子句之后被“销毁”。