Search code examples
pythonpython-3.xclassoopinstance

Python class instance returning the empty line when method is called


Here is my code

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())

When I run an empty line is printed instead of printing value from the list of type class.

The TreasureChestData.txt file is:

2*2
4
10
100/10
10
15
1000*4
4000
20
125/25
5
30
3000+4000
7000
18

Need help with this issue.


Solution

  • The root issue you see is that instance names that start with __ are mangled (https://docs.python.org/3/tutorial/classes.html#private-variables). That is what you are requesting by using that convention.

    So to access them you would need to do something like:

    arrayTreasure[i]._treasureChest__question = question
    

    in order to actual set the value.

    For example:

    x = treasureChest("", bool(), 0)
    print(x.getQuestion())
    
    x.__question = "q"
    print(x.getQuestion())
    
    x._treasureChest__question = "q"
    print(x.getQuestion())
    

    However, I recommend you take a look at this code to see if it helps with importing your treasure data.

    class TreasureChest:
        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
    
    def get_treasure_chests(treasure_file_name):
        treasure_chests = []
        with open(treasure_file_name) as file_in:
            for question in file_in:
                treasure_chests.append(TreasureChest(
                    question.strip(),
                    file_in.readline().strip(),
                    file_in.readline().strip()
                ))
        return treasure_chests
    
    treasure_chests = get_treasure_chests("TreasureChestData.txt")
    
    for treasure_chest in treasure_chests:
        print(treasure_chest.getQuestion())
    

    That gives me back:

    2*2
    100/10
    1000*4
    125/25
    3000+4000