我创建了一个查找矩形区域的类。我遇到的问题是每当我尝试检查类的实例时,printArea()方法都会给我一个类型错误。我不知道出了什么问题。
class Rectangle:
length = 0;
breadth = 0;
def __init__(self, length, breadth):
self.length = length
self.breadth = breadth
def setLength(self, length):
self.length = length
def getLength(self):
return self.length
def setBreadth(self, breadth):
self.breadth = breadth
def getBreadth(self):
return self.breadth
def calculateArea(self):
Area = self.getLength() * self.getBreadth()
return Area
def printArea(self):
Area = self.getLength() * self.getBreadth()
print ("The area is %d" % (Rectangle.Area))
如果我尝试x = Rectangle(7,4)
然后尝试x.printArea()
,我会得到:
Traceback (most recent call last):
File "<pyshell#229>", line 1, in <module>
x.printArea()
TypeError: printArea() takes 0 positional arguments but 1 was given
答案 0 :(得分:0)
如果我运行你的代码,我会得到AttributeError: type object 'Rectangle' has no attribute 'Area'
。如果您将其更改为
def printArea(self):
area = self.getLength() * self.getBreadth()
print("The area is %d" % (area))
当您编写Rectangle.Area
时,这不会显示当前矩形的区域(由self.getArea()
给出),而是获得类Area
的成员{ {1}}(不存在)。
话虽如此,你可以通过将Rectangle
作为一个属性来调用它来得到你想要的东西:
area
另请注意,get ...和set ...在python中非常不受欢迎,访问该成员完全没问题。如果你真的需要它们,你应该使用带有getter和setter的属性
class Rectangle:
def __init__(self, length, breadth):
self._length = length
self.breadth = breadth
@property
def area(self):
return self.length * self.breath
def printArea(self):
print ("The area is %d" % (self.area))