Python-打印特定对象列表属性

时间:2018-11-26 18:46:25

标签: python oop

如何从对象列表中打印特定的对象属性。我本以为可以提供特定的列表索引,但是尝试尝试时出现以下错误:AttributeError: 'list' object has no attribute 'grade'

class tests():

    def __init__(self,grade):
         self.grade = grade


test_list = []

for x in range(1,6):
    test_object = tests(x)
    test_list.append(test_object)


print (test_list[1].grade)

1 个答案:

答案 0 :(得分:0)

这里有一些错误。

class tests():

    def __init__(self,grade):
         self.grade = grade


test_list = []

for x in range(1,6):
    test_object = tests(x)
    test_list.append(test_object)

list_a = [5,3,2,1,4]

# THIS LINE BELOW IS THE PROBLEM    
for x in [test_list]:
    # in this line below X = test_list and indeed test_list.grade doesn't make sense.
    test_list.append(sorted(x.grade,key=list_a.index))


print (test_list[1].grade)