【发布时间】: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