Python |如何打印列表的值而不是内存位置 | __repr__ 和 __str__ 不起作用

问题描述 投票:0回答:1
class Student:
    def __init__(self, name, year):
        self.name = name
        self.year = year
        self.grades = []
    
    def add_grade(self, grade):
       if type(grade) is Grade: 
           self.grades.append(grade)
        
roger = Student("Roger van der Weyden", 10) 
sandro = Student("Sandro Botticelli", 12)
pieter = Student("Pieter Bruegel the Elder", 8)        

class Grade:
    minimum_passing = 65
    
    def __init__(self, score):
        self.score = score
    
    def is_passing(self):
        if self.score >= self.minimum_passing:
            print("Cool")
        else:
            print("Kys")
              
pieter.add_grade(Grade(100))
pieter.add_grade(Grade(89))

pieter_result = Grade(55)
pieter_result.is_passing()
print(pieter.grades) #This is printing out the location address instead of the value

我测试的新代码的示例

class Student:
    def __init__(self, name, year):
        self.name = name
        self.year = year
        self.grades = []
    
    def add_grade(self, grade):
        if isinstance(grade, Grade): 
            self.grades.append(grade)
           
roger = Student("Roger van der Weyden", 10) 
sandro = Student("Sandro Botticelli", 12)
pieter = Student("Pieter Bruegel the Elder", 8)        

class Grade:
    minimum_passing = 65
    
    def __init__(self, score):
        self.score = score
    
    def is_passing(self):
        if self.score >= self.minimum_passing:
            print("Passing")
        else:
            print("Failing")
    
    # def __str__(self):
    #   return str(self.grades)

    # def __repr__(self):
    #   return str(self.score)

#Both of these additions still provide the same output.
            
pieter.add_grade(Grade(100))
pieter.add_grade(Grade(89))

pieter_result = Grade(55)
pieter_result.is_passing()
print(pieter.grades)

我正在做一项活动,我开始思考解决我遇到的这个问题的方法。很多资源一直告诉我创建一个 strrepr 方法,但它不起作用。我不断得到 [<main.Grade 对象位于 0x00000241FC4774D0>, <main.Grade 对象位于 0x00000241FC477510>] 的输出,但我需要的是值 100 和 89。

我仍在尝试理解构造函数的概念并调用它们,但即使按照我的理解,该位置出现的原因也是没有意义的。手动向列表添加值似乎可行,但我不明白 for 循环为什么还没有这样做。

python class memory-management
1个回答
0
投票

如果将 Student 类定义更改为:

class Student:
    def __init__(self, name, year):
        self.name = name
        self.year = year
        self.grades = []
    
    def add_grade(self, grade):
       if type(grade) is Grade: 
           self.grades.append(grade.score)  #note change here

然后打印输出将如下,我认为这是你所期望的:

Kys
[100, 89]
© www.soinside.com 2019 - 2024. All rights reserved.