我有兩個類: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'
'MyClass'是否有屬性'items'? – aIKid
什麼tpe是傳遞給構造函數的Dict?也Dict = {}很可能不會做你認爲它做的事情。你期待它做什麼? – grim
你在哪裏使用代碼中的「items」? – Christian