Python AttributeError:类对象没有attribu

2024-10-04 11:30:33 发布

您现在位置:Python中文网/ 问答频道 /正文

当我试图运行我正在编写的类的代码时,我得到一个AttributeError,我不知道为什么。具体误差如下:

    self.marker = self.markers[marker[1:]]
AttributeError: 'TTYFigureData' object has no attribute 'markers'

以下是我正在写的部分课程:

^{pr2}$

我哪里出错了?在


Tags: no代码selfobjectattributemarker课程误差
2条回答

__init__方法中,在设置self.markers之前调用self.set_marker()

self.set_marker(marker)
self.markers = {
    "-" : u"None" ,
    "," : u"\u2219"
}

所以当set_marker()运行时,没有self.markers。将呼叫下移一行:

^{pr2}$

Martijn's answer解释了问题并给出了最小解。但是,鉴于self.markers似乎是常量,我将使其成为类属性,而不是为每个实例重新创建它:

class TTYFigureData(object):
    """Data container of TTYFigure."""

    MARKERS = {
        "-": u"None" ,
        ",": u"\u2219",
    }

    def __init__(self, x, y, marker='_.', plot_slope=True):
        """Document parameters here as required."""
        self.x = x
        self.y = y
        self.plot_slope = plot_slope
        self.set_marker(marker)

    def set_marker(self, marker):
        """See also here - usage guidance is also good."""
        if marker in [None, "None", u"None", ""]:
            self.plot_slope = True
            self.marker = ""
        elif marker[0] == "_":
            self.marker = self.MARKERS[marker[1:]]
        else:
            self.marker = marker

(注意,样式也根据the official guidance更改)

相关问题 更多 >