下面是我的代码
class treasureChest:
#Private question : String
#Private answer : Integer
#Private points : Integer
def __init__(self,questionP, answerP, pointsP):
self.__question = questionP
self.__answer = answerP
self.__points = pointsP
def getQuestion(self):
return self.__question
def checkAnswer(self, answer):
return self.__answer == answer
def getPoints(self, attempt):
if attempt == 1:
return self.__points
elif attempt == 2:
return self.__points // 2
elif attempt == 3 or attempt == 4:
return self.__points // 4
else:
return 0
arrayTreasure = [treasureChest("",bool(),0) for i in range(6)] # arrayTreasure(5) as treasureChest
def readData():
global arrayTreasure
filename = "TreasureChestData.txt"
try:
file = open(filename, "r")
dataFetched = (file.readline()).strip()
for i in range(len(arrayTreasure)):
question = dataFetched
answer = (file.readline()).strip()
points = (file.readline()).strip()
arrayTreasure[i].__question = question
arrayTreasure[i].__answer = answer
arrayTreasure[i].__points = points
dataFetched = (file.readline()).strip()
file.close()
except FileNotFoundError:
print("File could not be found")
readData()
print(arrayTreasure[1].getQuestion())
当我运行一个空行打印,而不是打印类型类列表中的值。
TreasureChestData.txt文件为:
2*2
4
10
100/10
10
15
1000*4
4000
20
125/25
5
30
3000+4000
7000
18
需要此问题的帮助。
1条答案
按热度按时间qojgxg4l1#
您看到的根本问题是以
__
开头的示例名被篡改(https://docs.python.org/3/tutorial/classes.html#private-variables),这正是您使用该约定所要求的。因此,要访问它们,您需要执行以下操作:
以便实际设置该值。
例如:
不过,我建议您看一看这段代码,看看它是否有助于导入您的宝藏数据。
这就给了我: