如何显示对象的类类型,并创建一个用逗号分隔的排序列表?

问题描述 投票:0回答:1

我的问题陈述:

创建一个称为DataManager的类,该类用于跟踪与一组文件关联的简单统计信息。每个文件应包含制表符分隔的相似数据行。实施下面的方法以获得满分。

init:DataManager构造函数除self外不接受任何参数。构造函数创建以下属性:#1)字典属性,称为数据,用于存储数据(字典将索引整数映射到值列表)。#2)一个整数属性,称为recordnum,用于存储当前索引值(应该始终是要添加的下一条记录的索引)。#3)一个名为file_list的列表属性,用于存储一个或多个要添加的文件。

repr:显示对象的类型(DataManager)和已添加到对象的文件的逗号分隔列表。此文件名列表必须排序。

我一直为我的repr方法收到TypeError或AttributeError。我该如何纠正?

我当前的代码:

  #Method: __init__
    #Data is a dictionary, recordnum is an integer, 
    #file_list is a list to store added file(s). 
    #Self, Dict, Int, List -> Self
    def __init__ (self):

        self.data = {}
        self.file_list = []
        self.recordnum = 0


    #Method: __repr__
    def __repr__ (self): 

         return type(object)
         return str(sorted(self.file_list.split(','))
python python-3.x list class repr
1个回答
0
投票

通常,repper返回对象的精确字符串表示形式,使您可以使用eval重新创建它:

eval(repr(instance)) --> instance

在您的情况下,可能是这样的:

class MyQuestion:

    def __init__ (self, file_list):
        self.data = {}
        self.file_list = file_list[:]
        self.recordnum = 0

    def __repr__ (self): 
         return f'{self.__class__.__name__}({sorted(self.file_list)})'

MyQuestion([2, 4, 6, 1, 3])

# ---> 'MyQuestion([1, 2, 3, 4, 6])'
© www.soinside.com 2019 - 2024. All rights reserved.