【问题标题】:Pytest fails with AttributeError: 'str' object has no attribute 'x'Pytest 因 AttributeError 失败:“str”对象没有属性“x”
【发布时间】:2021-08-29 00:35:36
【问题描述】:

我无法通过考试。当我运行代码时,它似乎可以找到,但在 pytest 中它失败了:

desk.py

class Dimension:
    x = 0
    y = 0
    z = 0
    
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

class Desk:
    def __init__(self, dimension):
        self.dimension = dimension

    @property
    def dimension(self):
        return self.__dimension

    @dimension.setter
    def dimension(self, d):
        s = d.split(".")
        self.__dimension = Dimension(int(s[0]), int(s[1]), int(s[2]))

    @property
    def is_large(self):
        if self.dimension.x > 100:
             return True
        return False

test_desk.py

...
def test_is_large():
    desk = Desk("5.5.5")
    assert desk.is_large == False
...

我收到AttributeError: 'str' object has no attribute 'x'

如果我更改为 getter 和 setter 方法,它可以找到,但我想使用装饰器。

更新: 我使用python3 -m pytest 使用 python3 运行 pytest,它工作正常

【问题讨论】:

  • 如果你使用settergetter,你应该坚持使用它们。当您从类函数调用self.dimension.x 时,您访问的是在__init__ 中定义的dimension 对象,它是一个字符串,没有x 属性;因此出现错误消息。
  • Dimension 类是否应该接受 x、y、z 参数?
  • @crissal 不知道你为什么这么认为。正如预期的那样,它确实调用了 setter。问题出在其他地方。

标签: python


【解决方案1】:

这是 self.__dimension 的双下划线。阅读:What is the difference in python attributes with underscore in front and back

还有这个:How to access "__" (double underscore) variables in methods added to a class

将 self.__dimension 更改为 self._dimension 即可。

编辑:不是下划线。您的代码在 Python3 中完美运行。在 Python2 中,我以这种方式工作:

class Dimension:
    x = 0
    y = 0
    z = 0
    def __init__(self, x, y, z):
        self.x = 0
        self.y = 0
        self.z = 0

class Desk:
    def __init__(self, dimension):
        s = dimension.split(".")
        self.__dimension = Dimension(int(s[0]), int(s[1]), int(s[2]))
    @property
    def dimension(self):
        return self.__dimension
    @dimension.setter
    def dimension(self, d):
        s = d.split(".")
        self.__dimension = Dimension(int(s[0]), int(s[1]), int(s[2]))
    @property
    def is_large(self):
        if self.dimension.x > 100:
             return True
        return False

【讨论】:

  • 我更改了self._dimension,但仍然出现同样的错误
  • 好的。你说的对。停止使用python2,不再支持它。您的代码在 python3 中完美运行,但在 python2 中引发了异常。
  • 啊,非常感谢您的帮助,我很感激。它现在可以工作了:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-10
  • 2021-10-04
  • 2019-12-02
  • 2021-09-25
  • 2014-03-04
  • 2013-09-22
相关资源
最近更新 更多