Rectangle'对象没有'width'属性
我刚开始学习Python中的类的部分,按照课本的要求写了一个类和主程序。看起来还不错,但我总是收到一个错误提示,说我的类没有某个特定的属性,这让我觉得很奇怪,因为它应该有。这个程序只是一个简单的矩形,计算周长和面积,所以并不复杂。不过,也许你们能发现我看不到的问题。
这是我的类的样子:
class Rectangle:
def __init__(self, length = 1, width = 1):
self.length = length
self.width = width
def setWidth(self, width):
self.width = width
def setLength(self, length):
self.length = length
def getPerimeter(self):
return (2 * self.length) + (2 * self.width)
def getArea(self):
return self.length * self.width
这是实际的主程序
from Rectangle import Rectangle
recWidth = eval(input("Enter the length of the rectangle: "))
recLength = eval(input("Enter the width of the rectangle: "))
x = Rectangle()
y = Rectangle()
x.width(recWidth)
x.length(recLength)
print("The perimeter of a rectangle with a width of", recWidth,
" units and a length of ", recLength, " units is ", x.getPerimeter(), ".")
谢谢,希望我提供的信息足够帮助我提出一个有效的问题。
1 个回答
2
你试图用两个参数(x 和 recWidth/recLength)来调用 width
和 length
这两个方法,但它们其实只是变量。你可能是想这样做:
x.width # get the width of the Rectangle
x.length # get the height of the Rectangle
或者这样:
x.setWidth(recWidth) # set the width of the Rectangle
x.setLength(recLength) # set the height of the Rectangle