擅长:python、mysql、java
<p>您可以这样做:</p>
<pre class="lang-py prettyprint-override"><code>class Student:
...
def __repr__(self):
return str((self.name, self.get_grade_avg()))
class ClassRoom:
def __init__(self, students):
self.students = students
def __str__(self):
return str(self.students)
john = Student("John", [100, 90 ,95])
mike = Student("Mike", [90, 80, 85])
c = ClassRoom([john, mike])
print(c)
# [('John', 95.0), ('Mike', 85.0)]
print(c)
</code></pre>
<p>在对某个对象调用<code>print</code>时,将调用其<code>__str__</code>方法,如果未定义该方法,则调用<code>__repr__</code>。默认情况下,某个对象的<code>__repr__</code>是这样的:<code><__main__.Student object at 0x7f4b35a3a630></code></p>
<p>在上面的代码中,a<code>Student</code><em>知道如何显示自己(name,avg),因此如果您愿意,可以打印它:<code>print(john)</code></p>
<p>对于<code>ClassRoom</code>,只需覆盖<code>__str__</code>即可显示学生列表。因为每个学生都知道如何表现自己,所以他们会做好的</p>