0
Python初學者問題在這裏。我嘗試在我正在創建的基於文本的遊戲中使用pickle保存和加載對象,並且列表變量未按預期方式加載。這是我寫來測試該問題的代碼(在這個例子中)初始化之外初始化保存和載入OK(在這個例子中Y),但變量列表中pickle沒有保存(或加載?)對象列表變量__init__
import pickle
class my_class(object):
def __init__(self, x):
self.x = x
self.y = [1,2,3]
a = [4,5,6]
b = 8
def save(object1):
print("Game saved")
pickle_out = open("saveobject1","wb")
pickle.dump(object1, pickle_out)
pickle_out.close()
def load():
print("Loading......")
pickle_in = open("saveobject1","rb")
object1 = pickle.load(pickle_in)
return object1
object1 = my_class(10)
print ("object1.x = " + str(object1.x))
print ("object1.y = " + str(object1.y))
print ("object1.a = " + str(object1.a))
print ("object1.b = " + str(object1.b))
print ("\n")
answer = input("Would you like to save (s) or load (l)?: ")
if answer == "s":
save(object1)
object1.x = 20
object1.y[2] = 6
object1.a[2] = 12
object1.b = 16
if answer == "l":
object1 = load()
print ("object1.x = " + str(object1.x))
print ("object1.y = " + str(object1.y))
print ("object1.a = " + str(object1.a))
print ("object1.b = " + str(object1.b))
print ("\n")
表變量不。但是,init以外的非列表變量會保存並加載。預先感謝您的建議。
非常感謝您的回答,現在更有意義。我想在遊戲中保存的列表是世界地圖,它是一個總共包含42個元素的列表列表,所以我想讓它成爲一個實例變量比單獨保存更容易。除非有一種簡單的方法來保存我不知道的清單? – Lang0n