【发布时间】: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,它工作正常
【问题讨论】:
-
如果你使用
setter和getter,你应该坚持使用它们。当您从类函数调用self.dimension.x时,您访问的是在__init__中定义的dimension对象,它是一个字符串,没有x属性;因此出现错误消息。 -
Dimension 类是否应该接受 x、y、z 参数?
-
@crissal 不知道你为什么这么认为。正如预期的那样,它确实调用了 setter。问题出在其他地方。
标签: python