Python AttributeError:类对象没有属性 [英] Python AttributeError: class object has no attribute

查看:72
本文介绍了Python AttributeError:类对象没有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I try to run the code of a class I'm writing, I get an AttributeError and I'm not sure why. The specific error is as follows:

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

这是我正在编写的课程的一部分:

Here is part of the class I'm writing:

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

我要去哪里错了?

推荐答案

Martijn的答案解释了问题并给出了最小的建议解决方案.但是,考虑到 self.markers 似乎是常量,我将其设为 class属性,而不是为每个实例重新创建它:

Martijn's answer explains the problem and gives the minimal solution. However, given that self.markers appears to be constant, I would make it a class attribute rather than recreating it for every instance:

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

(请注意,更改样式还应符合官方指南)

这篇关于Python AttributeError:类对象没有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆