【问题标题】:python error where __str__ returns a NoneTypepython 错误,其中 __str__ 返回 NoneType
【发布时间】:2017-08-25 12:54:08
【问题描述】:
class Pixel:
  """Representing a 'pixel' aka one character on the screen
  is mostly gonne be used in Map using a tuple location and a
  character that can be changed"""

  def __init__(self, char='#', location=(0,0)):
    assert type(char) == str
    assert type(location[0]) == int and type(location[1]) == int
    self.location = location
    self.x = self.location[0]
    self.y = self.location[1]
    self.char = char

  def __str__(self):
    return(self.char)



class Map:
  """Representing a map by having diffferent characters
  on different lines and being able to manipulate the 
  characters, thus playing a game"""

  def __init__(self, file=None):
    self.pixels = {}
    if not file:
      self.rows = 3
      self.colls = 3
      for r in range(self.rows):
        for c in range(self.colls):
          self.pixels[(r, c)] = Pixel('#', (r, c))

  def __str__(self):
    print(self.pixels)
    for c in range(self.colls):
      print('')
      for r in range(self.rows):
        print(self.pixels[(r, c)], end='')





a = Map()
print(a)

我正在尝试创建一个定义网格的类,其中网格中的每个位置都有一个字符,但是当我运行代码时,我收到一个错误,告诉我__str__ 返回一个 NoneType。我知道在启动 Map 时我还没有处理文件输入,但这不是问题,这是我得到的输出。

{(0, 1): <__main__.Pixel object at 0x7f31612a3080>,
 (1, 2): <__main__.Pixel object at 0x7f31612a3470>,
 (0, 0): <__main__.Pixel object at 0x7f31612a3048>,
 (2, 0): <__main__.Pixel object at 0x7f31612a34a8>,
 (1, 0): <__main__.Pixel object at 0x7f31612a32b0>,
 (2, 2): <__main__.Pixel object at 0x7f31612a3390>,
 (0, 2): <__main__.Pixel object at 0x7f31612a30b8>,
 (2, 1): <__main__.Pixel object at 0x7f31612a3358>,
 (1, 1): <__main__.Pixel object at 0x7f31612a32e8>}

###
###
###Traceback (most recent call last):
  File "main.py", line 45, in <module>
    print(a)
TypeError: __str__ returned non-string (type NoneType)
exited with non-zero status

我也很困惑为什么 Map 中的 __str__ 中的 print 将我引用到 __main__.Pixel 对象而不是使用它们 __str__ 方法,但这可能只是我缺乏知识

我错过了什么?

【问题讨论】:

  • str 方法在调用类时应该总是返回一个字符串。

标签: string python-3.x class nonetype


【解决方案1】:

您应该使用__repr__。同样在Map.__str__,你没有返回任何东西。例如

In [10]: class Test:
   ....:     def __str__(self):
   ....:         return "str"
   ....:     def __repr__(self):
   ....:         return "repr"
   ....:     

In [11]: t=Test()

In [12]: t
Out[12]: repr

In [13]: print(t)
str

【讨论】:

  • 这对TypeError或代表或__main__.Pixel object有帮助吗?
  • 是的。 __main__.Pixel object 将更改为 Pixel.__repr__ 方法中返回的任何内容
  • 谢谢,这个问题已经解决了:-)
【解决方案2】:

我忘了returnanything,我有__str__print 我需要的所有东西,但我没有为我的print(a) 返回任何东西,因此我收到了 NoneType 错误。

【讨论】:

    猜你喜欢
    • 2021-11-09
    • 2017-07-02
    • 1970-01-01
    • 2018-03-02
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    相关资源
    最近更新 更多