2013-10-25 337 views
3

我有兩個類:MyClass和MyClass2。對於MyClass,我帶了一個文件並返回了該文件中的每個單詞。在MyClass2中,我繼承了MyClass,並且基本上編寫了一個代碼,用於存儲字典中的所有單詞以及單詞作爲值的頻率。 我已經測試過的第一堂課,它能夠返回每一個單詞。 MyClass2我以爲我寫的是正確的,但是我認爲我沒有繼承MyClass的權利,或者我的方法寫的是錯誤的。每次我嘗試運行我的代碼時,它都會返回一個錯誤。 由於這是一項家庭作業,(我也不想被視爲作弊..)我不會發布我的所有代碼,除非有必要回答我的問題,我也不會期望任何人重寫或完全修復我的代碼。我只需要一些指導,說明我的構造函數是否錯誤,或者整個代碼是錯誤的,還是我只是沒有正確地格式化我的代碼並繼承類錯誤...? 我是新來的蟒蛇,我只需要幫助。Python:對象沒有屬性

from myclass import MyClass 
class MyClass2(MyClass): 
     def __init__(self, Dict): #Is the problem within the constructor? 
      self.Dict = Dict 
      Dict = {} 
     def dict(self, textfile): 
      text = MyClass(textfile) #Was I wrong here?? 
      .................. 
       .............. 
       .............. 
       return self.Dict 
     def __iter__(self): 
      for key, value in self.Dict.items(): 
       yield key, value 

當我運行一個測試代碼,我得到一個錯誤,指出:

AttributeError: 'MyClass2' object has no attribute 'items' 

請讓我知道,如果我缺少anythign或者如果沒有足夠的信息。

我測試了它使用此代碼給定:

filename = MyClass1('name of file') 
y = MyClass2(filename) 
for x in y: 
    print x 

這裏是回溯:

Traceback (most recent call last): 
File "C:\myclass.py", line 25, in <module> 
    for x in y: 
File "C:\myclass2.py", line 19, in __iter__ 
    for key, value in self.Dict.items(): 
AttributeError: 'MyClass2' object has no attribute 'items' 
+1

'MyClass'是否有屬性'items'? – aIKid

+0

什麼tpe是傳遞給構造函數的Dict?也Dict = {}很可能不會做你認爲它做的事情。你期待它做什麼? – grim

+0

你在哪裏使用代碼中的「items」? – Christian

回答

0

你的變量的命名是很奇怪的。我會盡量放鬆吧:

from myclass import MyClass 
class MyClass2(MyClass): 
     def __init__(self, Dict): 
      self.Dict = Dict 
      Dict = {} 
     def __iter__(self): 
      for key, value in self.Dict.items(): 
       yield key, value 

filename = MyClass1('name of file') 
y = MyClass2(filename) 

這裏,filename不是文件名(這我就懷疑是strunicode)。也許這是一個包含文件名的對象。 (命名爲MyClass1不是很有幫助。)

filename所指的此對象給予MyClass2.__init__()。它被放入self.Dict。然後,參數Dict設置爲{},這是毫無意義的。

唉,我不知道你想達到什麼。也許你想要類似

class MyClass2(MyClass): 
     def __init__(self, filename): 
      self.filename = filename 
      self.Dict = {} 
     def __iter__(self): 
      for key, value in self.Dict.items(): 
       yield key, value 

注意:最好以小寫命名變量。並且不要重命名Dict只是做dict,而是以讀者可以看到它的含義的方式命名。

+0

謝謝。這實際上確實擺脫了我的錯誤。運行我的測試代碼後,它不會打印除MyClass的輸出外的任何內容。 MyClass2應該在運行測試代碼後打印字典的鍵和值。這是否意味着MyClass2中的def __iter __(self)是錯誤的或者它是否在這個類中的其他位置? – user2918801

+0

@ user2918801不,這是您的'__init__',它以錯誤的順序執行某些操作,有些甚至是毫無意義的。分配給局部變量在這裏毫無意義;爲了保存東西,你可以將它分配給'self'屬性,比如'self.filename'或'self.datadict'。 – glglgl

相關問題