如何打印对象本身而不是对象的位置python?

How to print the object itself instead of the location of the object python?

我正在制作一个程序,它将从文本文件中读取包含问题、答案和奖励分数的行,它们分别位于第 i、i+1 和 i+2 行。这些行将被读取,然后保存在 TreasureChest 类型的数组中。但是当我打印时,我得到输出:


[<__main__.TreasureChest object at 0x7f89197c5470>, <__main__.TreasureChest object at 0x7f89197c54a8>, <__main__.TreasureChest object at 0x7f89197c5400>, <__main__.TreasureChest object at 0x7f89197c5438>, <__main__.TreasureChest object at 0x7f89197c57b8>, <__main__.TreasureChest object at 0x7f89197c5828>, <__main__.TreasureChest object at 0x7f89197c5860>, <__main__.TreasureChest object at 0x7f89197c5898>, <__main__.TreasureChest object at 0x7f89197c58d0>, <__main__.TreasureChest object at 0x7f89197c5908>, <__main__.TreasureChest object at 0x7f89197c5940>, <__main__.TreasureChest object at 0x7f89197c5978>, <__main__.TreasureChest object at 0x7f89197c59b0>, <__main__.TreasureChest object at 0x7f89197c59e8>, <__main__.TreasureChest object at 0x7f89197c5a20>]



我知道这是关于打印字符串而不是对象位置的常见问题,但是 none 这里的答案对我的情况有效或有用。

代码如下:




import linecache


searchfile = open("TreasureChestData.txt", 'r')

class TreasureChest:

    def __init__(self, question, answer, points):

        self.question = question 
        self.answer = answer 
        self.points = points 



    

def read_data():

    searchfile = open("TreasureChestData.txt", 'r')
    arrayTreasure = []
    

    for i in range (1, 16):


        question = linecache.getline('TreasureChestData.txt', i)
        answer = linecache.getline('TreasureChestData.txt', (i+1))
        pointer = linecache.getline('TreasureChestData.txt', (i+2))

        arrayTreasure.append(TreasureChest(question, answer, pointer))

        i = i + 3

    print (len(arrayTreasure))

    return arrayTreasure

    searchfile.close()
    
data = read_data()
print (data)

您所看到的只是特殊 __str__ 方法的默认实现。您所要做的就是 def __str__(self):,然后 return 您想要使用的任何字符串。

定义 class 的 __repr__(它控制它在容器中以及其他地方的显示方式)及其 __str__(它控制它在打印时的显示方式) .它们可以相同,如此处所示。

class TreasureChest:

    def __init__(self, question, answer, points):
        self.question = question 
        self.answer = answer 
        self.points = points 

    def __repr__(self):
        return f'{type(self).__name__}("{self.question}")'

    __str__ = __repr__

t = TreasureChest("What is the airspeed veloicity of an unladen swallow?", 42, 100)
print(t)