python __str__ returned non-string (type list)class maze:def get_neighbours(self,src):"""This method returns a list of the celllocations that are adjacent to the source cellpassed as a parameter """directions = [(0,-1),(1,0),(0,1),(-1,0)]neighbours =
来源:学生作业帮助网 编辑:作业帮 时间:2024/11/15 22:55:32
python __str__ returned non-string (type list)class maze:def get_neighbours(self,src):"""This method returns a list of the celllocations that are adjacent to the source cellpassed as a parameter """directions = [(0,-1),(1,0),(0,1),(-1,0)]neighbours =
python __str__ returned non-string (type list)
class maze:
def get_neighbours(self,src):
"""This method returns a list of the cell
locations that are adjacent to the source cell
passed as a parameter """
directions = [(0,-1),(1,0),(0,1),(-1,0)]
neighbours = []
for dx,dy in directions:
x = src[0] + dx
y = src[1] + dy
if x in range(self.size) and y in range(self.size):
neighbours.append((x,y))
return sorted(neighbours)
def blank_maze(self):
self.maze = {}
for y in range(self.size):
for x in range(self.size):
self.maze[(x,y)] = self.get_neighbours((x,y))
def __repr__(self):
"""This method should return a string representation of
the maze.It should simply format the dictionary containing
the maze connections with each curly brace on their own line,
and each entry of the dictionary on a separate line.The entries
are given in sorted order based on the keys.For example,a maze
with a size of 2 might be represented by the following string:
{
(0,0):[(0,1)]
(0,1):[(0,0),(1,1)]
(1,0):[(1,1)]
(1,1):[(0,1),(1,0)]
}
"""
dic = {}
for x in range(0,self.size):
for y in range(0,self.size):
dic[(x,y)] = self.get_neighbours((x,y))
return sorted(dic)
Test:
m = maze(2)
m.blank_maze()
print(m)
get_neighbours和blank_maze两个没有问题.写完__repr__后运行一直在print(m)这里跳出error说__str__ returned non-string (type list) 该怎么解决?
python __str__ returned non-string (type list)class maze:def get_neighbours(self,src):"""This method returns a list of the celllocations that are adjacent to the source cellpassed as a parameter """directions = [(0,-1),(1,0),(0,1),(-1,0)]neighbours =
sorted(dic)这个函数返回的是个list,而你的__repr__函数应该返回的是一个str,也就是字符串,所以你应该把你要输出的结果在函数内整理好返回,返回的必须是字符串格式的.