如何在python中打印不同对象的列表?

时间:2018-01-13 18:18:07

标签: python string list oop printing

我有一个随机选择的对象列表(River)(BearFish),我想用以下格式打印列表:

[B, F, B, ...]

(是随机选择的对象的一个​​例子)。但是当我打印我的River实例时,我得到了:

[<class '__main__.Bear'>, <class '__main__.Fish'>, <class '__main__.Fish'>, <class '__main__.Fish'>, <class '__main__.Bear'>, ....]

为什么会这样?有什么建议?

class Bear:
    def __init__(self):
        print()

    def __str__(self):
        return str('B')

    def __repr__(self):
        return self

class Fish:
    def __init__(self):
        print()

    def __str__(self):
        return str('F')

    def __repr__(self):
        return self

class River:
    #simulate based on river length
    INITIAL_RIVER_LENGTH=20


    def __init__(self):
        self._river=[None]*self.INITIAL_RIVER_LENGTH

    def __str__(self):
        return str([i for i in self._river])

    def __repr__(self):
        return str(self)

    def fillRiver(self):
        self._river=[random.choice([Bear,Fish]) for i in range(0,self.INITIAL_RIVER_LENGTH)]


riv=River()
riv.fillRiver()
print(riv)

2 个答案:

答案 0 :(得分:3)

您正在河中存储

random.choice([Bear,Fish])

所以你得到一个班级列表:

[<class '__main__.Bear'>, ...
# ^^^^^

您必须调用随机选择的类来创建实例:

random.choice([Bear, Fish])()  # the () calls the class

现在你遇到了一个新问题:

>>> random.choice([Bear, Fish])()

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __repr__ returned non-string (type Fish)

因为您正在从self方法中退出__repr__。返回一个字符串值;也许可以使用return str(self),但最好只实现 __repr__,因为如果缺少__str__,Python会自动回退到__repr__

以下代码有效;请注意,我删除了__init__Fish的{​​{1}}方法,在创建其中一个时,使用Bear输出换行没有意义:

print()

演示:

class Bear:
    def __repr__(self):
        return 'B'

class Fish:
    def __repr__(self):
        return 'F'

class River:
    #simulate based on river length
    INITIAL_RIVER_LENGTH=20

    def __init__(self):
        self._river = [None] * self.INITIAL_RIVER_LENGTH

    def __repr__(self):
        return str(self._river)

    def fillRiver(self):
        self._river = [
            random.choice([Bear,Fish])() 
            for i in range(self.INITIAL_RIVER_LENGTH)
        ]

答案 1 :(得分:2)

不是在self中返回__repr__,而是返回表示每个生物的角色:

import random
class Bear:
  def __init__(self):
     print()
  def __str__(self):
    return str('B')
  def __repr__(self):
    return 'B'

class Fish:
  def __init__(self):
     print()
  def __str__(self):
     return str('F')
  def __repr__(self):
     return 'F'

class River:
   INITIAL_RIVER_LENGTH=20
   def __init__(self):
      self._river=[None]*self.INITIAL_RIVER_LENGTH
   def __str__(self):
      return str([i for i in self._river])
   def __repr__(self):
     return str([i for i in self._river])
   def fillRiver(self):
     self._river=[random.choice([Bear(),Fish()]) for i in range(0,self.INITIAL_RIVER_LENGTH)]

r = River()
r.fillRiver()
print(r)

输出:

[B, F, F, F, B, B, F, B, F, B, B, B, F, F, B, B, F, B, F, F]