我有一个代码,用于创建带有节点的图形,并跟踪边缘。这段代码本身似乎运行正常,但在阅读了一些 str vs 之后,我无法让 repr 覆盖工作以达到我的预期效果。 repo 和 repr ()返回非字符串线程,我似乎无法隔离我的麻烦。
!/usr/bin/python
class Edge:
def __init__(self, here, there, txt):
self.description = txt # why am i making this jump?
self.here = here # where do i start
self.there = there # where to i end
self.here.out += [self] # btw, tell here that they can go there
def __repr__(self):
return "E(" + self.here.name + " > " + self.there.name + ")"
class Node:
end = "."
start = "!"
def __init__(self, g, nid, name, stop=False, start=False):
self.nid = nid
self.graph = g # where do i live?
self.name = name # what is my name?
self.description = "" # tell me about myself
self.stop = stop # am i a stop node?
self.start = start # am i a start node?
self.out = [] # where do i connect to
def also(self, txt):
"""adds text to description"""
sep = "\n" if self.description else ""
self.description += sep + txt
def __repr__(self):
y = "N( :id " + self.nid + \
"\n :name " + self.name + \
"\n :about '" + self.description + "'" + \
"\n :out " + ",".join(str(n) for n in self.out) + " )"
class Graph:
def __init__(self):
self.nodes = [] # nodes, stored in creation order
self.keys = {} # nodes indexed by name
self.m = None # adjacency matrix
self.mPrime = None # transitive closure matrix
def __repr__(self):
return "\n".join(str(u) for u in self.nodes)
def node(self, name):
"""returns a old node from cache or a new node"""
if not name in self.keys:
self.keys[name] = self.newNode(name)
return self.keys[name]
def newNode(self, name):
""" create a new node"""
nid = len(self.nodes)
tmp = Node(self, nid, name)
tmp.start = Node.start in name
tmp.end = Node.end in name
self.nodes += [tmp]
return tmp
我理解 repr 只要字符串处理程序调用其函数就会返回一个字符串。更具体地说,它引用和实例作为字符串,查找 str , str 指向 repr ,并将其作为字符串返回到其调用方法。所以对于我的程序,我有一个图形,它被创建得很好,但是当我打印它时,它会卡在连接它加入的列表中,将它作为int而不是字符串返回?
我尝试将不同的部分作为字符串进行构建,因为可能 repr 未被调用,因为必须显式地转换字符串才能正常工作以及其他一些事情。我的故事的缺点是我的 repr 没有被“\ n”.join()正确处理,并以某种方式从",".join(str(n) for n in self.out)
获取一个int值,告诉我它不能连接一个str和一个int。
我真的很茫然,我已经阅读了许多关于使用repr的谷歌答案和文本,以及这里的许多答案,并且还没弄清楚我在这里究竟是什么。
以下是图形本身的构建方式,它在stagetext中读取,其中第一行是节点名称,出口以>开头,其间的所有内容都是节点位置的描述。
该图是我应该编辑的图,它应该只使用print graph("mystageText.txt")
进行打印,尽管我已经看到 repr 与repr(graph("myStageText.txt")
的大多数用法。因此,我对这个问题非常困惑,因为 repr 的简明例子似乎没有实例列表。
预先感谢您的帮助,希望这对StackOverflow来说足够简洁。 对不起,如果我在试图彻底解决我的问题时有点过于罗嗦。
答案 0 :(得分:0)
看起来您的问题确实来自
y = "N( :id " + self.nid + \
# ^
self.nid
是一个int。
另一个错误:Node.__repr__
没有返回任何内容。