Python AttributeError:类对象没有属性

时间:2015-09-28 13:10:28

标签: python class attributes attributeerror

当我尝试运行我正在编写的类的代码时,我得到AttributeError并且我不确定为什么。具体错误如下:

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

这是我写的课程的一部分:

class TTYFigureData(object):
    """
    data container of TTYFigure
    """
    def __init__(
        self,
        x,                      # x values
        y,                      # y values
        marker          = "_.", # datum marker
        plot_slope      = True
        ):
        self.x          = x
        self.y          = y
        self.plot_slope = plot_slope
        self.set_marker(marker)
        self.markers = {
            "-" : u"None" ,
            "," : u"\u2219"
        }

    def set_marker(
        self,
        marker
        ):
        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

我哪里错了?

2 个答案:

答案 0 :(得分:3)

__init__方法中,您在设置self.set_marker() 之前致电self.markers

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

因此,当set_marker()运行时,没有self.markers 。将呼叫向下移动一行:

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

答案 1 :(得分:1)

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一致的样式更改