【问题标题】:How can I modify my __repr__ to respresent correctly?如何修改我的 __repr__ 以正确表示?
【发布时间】: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


【解决方案1】:

我面临的问题与我不了解对象的性质有关。 itertools.combinations 是一个可迭代对象,为了表示存储的值,我需要

1.将其解压缩到一个变量中,例如:

def get_combinations(self, r):
     *res, = it.combinations(self.sorted_names, r)
     return res

要么

2.在一个循环中遍历它并保持原始代码不变

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

我更喜欢第二种解决方案

【讨论】:

  • 第二种解决方案不会创建有效的__repr__,因为它不提供字符串。注意,*res, = it.combinations(...)应该只是res = list(it.combinations(...))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-26
  • 1970-01-01
  • 1970-01-01
  • 2016-02-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多