|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 eobeom 于 2020-6-3 23:05 编辑
创建一个代表矩形的calss
class Rectangle包含以下变量和函数
representing代表矩形宽度和高度的变量
indicating指示矩形位置的变量
之后构造函数
返回矩形的面积calcArea()
1)定义上面的class Rectangle
2)创建一个矩形对象,其位置为(0,0),大小为(100,100)
3)创建一个矩形对象,其位置为(10,10),大小为(200,200)。
4)打印每个正方形的位置,宽度和长度
- class Rectangle:
- def __init__(self,width=0,length=0):
- self.__width=width
- self.__length=length
-
- def setWidth(self,width):
- self.__width=width
- def setLength(self,length):
- self.__height=height
- def getcalcArea(self):
- return self.__width*self.__length
- def __str__(self):
- return '(%d,%d)'%(self.__width,self.__length)
- class Indicating:
- def __init__(self,x,y):
- self.__x=x
- self.__y=y
-
- def setX(self,x):
- self.__x=x
- def setY(self,y):
- self.__y=y
- def __str__(self):
- return'(%d,%d)'%(self.__x,self.__y)
- rectangle=Rectangle(100,100)
- indicating=Indicating(0,0)
- print('位置是:',indicating,'大小为;',rectangle)
- print('矩形的面积是:',rectangle.getcalcArea())
- rectangle=Rectangle(200,200)
- indicating=Indicating(10,10)
- print('位置是:',indicating,'大小为;',rectangle)
- print('矩形的面积是:',rectangle.getcalcArea())
复制代码
题目中只叫我们创建一个 Rectangle 的 矩形类 ,所以你只需要创造一个类即可,其他的设置为方法
参考代码如下:
- class Rectangle:
- def __init__(self, x, y, width=0, length=0):
- self.x = x
- self.y = y
- self.__width = width
- self.__length = length
- def representing(self):
- return (self.__width, self.__length)
- def indicating(self):
- return (self.x, self.y)
- def calcArea(self):
- return self.__width * self.__length
- rectangle1 = Rectangle(0, 0, 100, 100)
- rectangle2 = Rectangle(10, 10, 200, 200)
- print('正方形1其位置为:',rectangle1.indicating(),'大小为:',rectangle1.representing())
- print('正方形1其面积为:',rectangle1.calcArea())
- print('正方形2其位置为:',rectangle2.indicating(),'大小为:',rectangle2.representing())
- print('正方形2其面积为:',rectangle2.calcArea())
复制代码
|
|