簡體   English   中英

AttributeError'myClass'對象沒有屬性'myList'

[英]AttributeError 'myClass' object has no attribute 'myList'

我正在使用python 2.7.3運行Windows 7,但遇到了一個繼承錯誤,我不知道為什么。 我已經做了很多搜索,但到目前為止還沒有發現太多相關性。

我的問題是,當我嘗試從一個類繼承到另一個類時,我不斷收到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”,但這似乎非常la腳。 提前致謝!

您實際上從未在任何地方將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這是確定過,只要你知道你在做什么 )。

您忘記了自我:

# 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 = ['','','','','']

如果沒有iflist子句,則沒有此mylist的對象將被“破壞”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM