关于类的问题定义

  • 本文关键字:定义 问题 于类 python
  • 更新时间 :
  • 英文 :

# This Program generates a class that is aimed at finding the Area and Perimeter
# in a rectangle.
import math
class Rectangle:
def __init__(self, height, width):
self.width = 2
self.height = 1
def getArea(self):
area = self.width * self.height
return area
def getPerimeter(self):
perimeter = 2 * (self.width + self.height)
return perimeter
def setHeight(self, height):
self.height = height
def setWidth(self, height):
self.width = width
def main():
rectangle1 = Rectangle()
print("The area of the Rectangle of radius" , Rectangle1.width, Rectangle1.height, "is",
Rectangle1.getArea())
main()

下面的代码是用Python编写的。到目前为止,我目前唯一的问题是,当我去运行它时,它说名称";矩形"未定义。这是对rectangle1=Rectangle((的引用,其中它被分配给类以及上面列出的所有各种实例和方法

但是由于这个定义问题,我不能使用Rectangle类的内容。我哪里错了

您的程序中有很多错误。

  1. 函数init接受两个参数,并且在创建对象Rectangle()时不提供任何参数

  2. 函数setWidth(self, height)和使用变量width的函数内部。

  3. Python区分大小写,所以矩形与矩形不同,在调用方位置,您的对象名称为"rectangle1",而您使用Rectangle1调用它

如果你修复了这些,你的程序应该可以

有多个错误。您调用的Rectangle类没有高度和宽度(您也可以将它们作为默认参数传递(。

你的缩进在课堂上被打断了。

您已经初始化了rectangle1,但调用了rectangle1,因此出现了其他错误。

import math
class Rectangle:
def __init__(self, height, width):
self.width = 2
self.height = 1
def getArea(self):
area = self.width * self.height
return area
def getPerimeter(self):
perimeter = 2 * (self.width + self.height)
return perimeter
def setHeight(self, height):
self.height = height
def setWidth(self, height):
self.width = width
def main():
rectangle1 = Rectangle(4,2)
print("The area of the Rectangle of radius" , rectangle1.width, rectangle1.height, "is",
rectangle1.getArea())
main()

我假设导致问题的行是:

print("The area of the Rectangle of radius" , Rectangle1.width, Rectangle1.height, "is",
Rectangle1.getArea())

很容易解释您收到此错误的原因:您定义了变量rectangle1,但在打印函数调用中,您需要对象rectangle1的值,但该值尚未定义。变量名区分大小写。

最新更新