0

我正在运行 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”,但这似乎非常糟糕。提前致谢!

4

2 回答 2

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只要你知道自己在做什么,这也可以)。

于 2012-10-23T20:40:46.880 回答
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 子句之后被“销毁”。

于 2012-10-23T20:42:06.003 回答