我創建的這裏面有兩個函數的類的功能。這些函數永遠在代碼底部的循環中運行。但是,第一個函數會創建一個字典,並且用戶將值添加到此字典中。第二個函數是爲了導入字典併爲每個值添加10。但是,當我運行此代碼時,出現錯誤,指出「材料未定義」。我該如何在兩個函數中正確使用字典?如何訪問字典中是在另一個函數定義在同一個班級
這裏是我的代碼:
class materialsClass:
def materialsChange(self):
while True:
q1 = raw_input("Type 'edit' to add or change a material, or 'continue' to continue: ")
if q1 == 'edit':
while True:
q2 = raw_input("Type 'add' to add a new material, 'edit' to edit amount of a material: ")
if q2 == 'add':
x = str(raw_input("Enter the Material: "))
y = int(0)
Materials = {x:y}
break
elif q2 == 'edit':
x = str(raw_input("Enter your Material: "))
y = int(raw_input("Enter your Change: "))
Materials[x] += y
break
else:
print "Please Type an Option"
elif q1 == 'continue': break
else:
print "Type an Option!"
print Materials
def materialCounter(self):
for k in Materials: Materials[k] += 10
print Materials
while True:
obj=materialsClass()
obj.materialsChange()
obj.materialCounter()
當我運行程序我收到指出NameError錯誤:不定義名稱「自我」 – user2757442 2015-02-07 17:58:17
@ user2757442哎呀,你不要有'__init__'檢查出編輯 – Kasramvd 2015-02-07 18:07:42