0

我有一个代码,它创建一个带有节点的图形,并跟踪边缘。这段代码本身似乎工作正常,但是在阅读了一些str vs reporepr () 返回的非字符串线程之后,我无法让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的函数,它就会返回一个字符串。更具体地说,它以字符串的形式引用和实例,查找strstr指向repr并作为字符串返回给它的调用方法。因此,对于我的程序,我有一个图表,它创建得很好,但是当我打印它时,它卡住了连接它加入的列表,将它作为 int 而不是字符串返回?

我尝试将不同的部分转换为字符串,认为可能没有调用repr,因为它必须明确地转换为字符串才能正常工作以及其他一些事情。我的故事的简短之处是我的repr没有被 "\n".join() 正确处理,并且以某种方式从 获取 int 值",".join(str(n) for n in self.out),告诉我它不能连接 str 和 int。

我真的很茫然,我已经阅读了许多关于使用 repr 的谷歌答案和文本,以及这里的许多答案,但还没有弄清楚我在这里究竟忽略了什么。

这是图本身的构建方式,它在 stagetext 中读取,其中第一行是节点名称,出口以 > 开头,中间的所有内容都是对节点位置的描述。

该图是我应该编辑的,它应该只是用 打印,尽管我已经看到了reprprint graph("mystageText.txt")大多数用法。因此,我对此事感到非常困惑,因为似乎没有带有实例列表的repr的清晰简洁示例。repr(graph("myStageText.txt")

提前感谢您的帮助,希望这对于 StackOverflow 来说足够简洁。抱歉,当我试图彻底解决我的问题时,我有点太罗嗦了。

4

1 回答 1

0

看起来你的问题真的来自

        y = "N( :id " + self.nid + \
        #                   ^

self.nid是一个整数。

另一个错误:Node.__repr__不返回任何东西。

于 2014-02-23T11:20:43.250 回答