如何解决如何根据上下文使用 __str__ 和 __repr__ 以不同方式打印我的自定义对象?
我对 python 比较陌生,我正在实现一个带有包含邻居字典的节点的图。我想打印图中的顶点,同时显示各个邻居的不同信息。我意识到这可能是一个递归问题,我正在尝试使用变量 rec_count
来防止无限递归,但我得到的结果很差。任何帮助将不胜感激。
这是我的 Node 类,它有一个邻居字典,其值为其他 Node 对象:
class Node(object):
__rec_count = 0 # to prevent infinite recursion of neighbors
def __init__(self,word,x_coordinate,y_coordinate,word_size,orientation):
self.word = word
self.coordinates = (x_coordinate,y_coordinate)
self.word_size = word_size
self.orientation = orientation
# list of immediate Node neighbors
self.neighbors = {}
# override the __str__ functions to print the Node
def __str__(self):
# only print immediate neighbors
if self.__rec_count == 1:
self.__rec_count = 0
return f'First Letter Coordinates: {self.coordinates}\n' \
f'Orientation: {self.orientation}\n'
else:
return f'\nWord: {self.word}\n' \
f'First Letter Coordinates: {self.coordinates}\n' \
f'Word size: {self.word_size}\n' \
f'Orientation: {self.orientation}\n' \
f'Neighbors: {self.neighbors}\n'
def __repr__(self):
self.__rec_count += 1
return str(self)
# override equality comparator. This assumes the starting char of a blank can't be in the same coordinates
def __eq__(self,other):
if isinstance(other,Node):
return self.coordinates == other.coordinates
# override hash function for faster lookup in dictionaries
# hash the coordinates as I assume the starting char of a blank can't be in the same coordinates
def __hash__(self):
return hash(self.coordinates)
...
例如,我希望打印节点字典的输出是:
{
Word: Horse
First Letter Coordinates: (0,0)
Word size: 5
Orientation: across
Neighbors: {(2,0): First Letter Coordinates: (2,0)
Orientation: down,(4,0): First Letter Coordinates: (4,0)
Orientation: down
}
Word: Sheet
First Letter Coordinates: (2,0)
Word size: 5
Orientation: across
Neighbors: {(0,0): First Letter Coordinates: (0,0)
Orientation: down
}}
但相反,我得到:
{(0,0)
Orientation: across,(2,0)
Orientation: down
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。