【发布时间】:2023-01-05 14:56:45
【问题描述】:
我的 __repr__ 方法使用在它的类中创建的对象工作正常,但是对于在导入库和使用它的方法的帮助下创建的对象,它只代表内存地址......
from roster import student_roster #I only got the list if students from here
import itertools as it
class ClassroomOrganizer:
def __init__(self):
self.sorted_names = self._sort_alphabetically(student_roster)
def __repr__(self):
return f'{self.get_combinations(2)}'
def __iter__(self):
self.c = 0
return self
def __next__(self):
if self.c < len(self.sorted_names):
x = self.sorted_names[self.c]
self.c += 1
return x
else:
raise StopIteration
def _sort_alphabetically(self,students):
names = []
for student_info in students:
name = student_info['name']
names.append(name)
return sorted(`your text`names)
def get_students_with_subject(self, subject):
selected_students = []
for student in student_roster:
if student['favorite_subject'] == subject:
selected_students.append((student['name'], subject))
return selected_students
def get_combinations(self, r):
return it.combinations(self.sorted_names, r)
a = ClassroomOrganizer()
# for i in a:
# print(i)
print(repr(a))
我尝试显示不依赖于另一个库的对象,并且它们显示正确。
【问题讨论】:
-
“t只代表内存地址……”它是显示正常。您的
__repr__只是提供了self.get_combinations(2)的字符串表示形式,它等同于it.combinations(self.sorted_names, r)。那你为什么预计除了itertools.combinations对象的字符串表示之外还有什么?那是你编码它给你什么.你是什么人期待? -
我期望由 itertools.combinations 计算的值,而不是内存地址,我需要更改什么?
-
你是否看
print(it.combinations.self.sorted_names, r)给了你什么?
标签: python inheritance python-itertools built-in repr