How can I modify my __repr__ to respresent correctly?

30 Views Asked by At

My __repr__ method works fine using objects created in it's class, but with objects that were created with the help of importing a library and using methods from it, it only represented the memory address...


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))

I tried displaying objects that don't rely on anther library, and they dispayed properly.

1

There are 1 best solutions below

1
Vaireanu Gabi On

The issue I was facing was linked to me not understanding the nature of the object. itertools.combinations is an iterable, and in order to represent the values stored I needed to either:

  1. unpack it inside a variable like:

    def get_combinations(self, r):
        *res, = it.combinations(self.sorted_names, r)
        return res
    
  2. Iter through it inside a loop and leave the original code intact like

    for i in a.get_combinations(2):
        print(i)
    

I prefer the second solution