我試圖編寫一個簡單的遊戲,並需要在文件中寫入一些信息。這是怎樣的代碼看起來像至今:試圖使用類函數在文件中編寫字符串
class Player:
def __init__(self, name, password, file):
with open(file) as inputFile:
self.playerAndPw = inputFile.read()
self.name = name
self.password = password
def add(self, name, password, file):
file.write(name + " | " + password)
def __str__(self):
print("The player's name is called " + self.name + "\n")
print("Welcome to Guess My Number!")
start = input("Press 1 for New Account, 2 for Log In: ")
if start == "1":
player = Player
playerID = input("Enter a name: ")
playerPassword = input("Enter a password: ")
fileName = "PlayerAndPassword.txt"
player.add(playerID, playerPassword, fileName)
在最後一行出現在最後的支架異常:「參數‘文件’填充因此,代碼不能得到信息的功能我使用的最後一行。
將是巨大的,如果有人可以幫助我!謝謝!
爲什麼你傳遞'名如果你已經將它們傳遞給了類構造函數,''''''''''''''''''作爲'Player.add'的參數嗎? – Tagc
另外'player = Player'這一行並沒有初始化'Player'的新實例。要做到這一點,你需要'player = Player(...)'並傳遞所需的參數。 – Tagc
但由於必須輸入文件,因此無法傳遞參數。看起來你的設計是有缺陷的:你不能用文件參數創建構造函數,因爲這意味着你永遠無法創建一個_new_播放器。更好地使用加載/保存方法,並使用json序列化/反序列化... –