我正在用Python创建一个程序,它将利用面向对象的编程来打印给定矩形的属性。该项目有以下限制:The purpose of this lab is to give you practice creating your own
object. You will be given a main function that expects an instance of
the (yet undefined) Rectangle object. Your job is to determine what
attributes and methods the Rectangle class requires and create a class
that will satisfy the requirements.Add only one feature at a time
You may need to comment out parts of the main function for testing
Constructor should take 0, 1, or 2 parameters (illustrating polymorphism)
Your class should be a subclass of something (illustrating inheritance)
Your class should have methods and properties (illustrating encapsulation)
Make your instance variables hidden (using the __ trick)
Add setter and getter methods for each instance variable
Use properties to encapsulate instance variable access
Not all instance variables are real... Some are derived, and should be write-only
You may not substantially change the main function (unless you're doing the blackbelt challenge)
Be sure to add the needed code to run the main function when needed
以下是评估准则代码:main()函数相对不变3
代码:矩形类是用默认值声明的,因此它支持0、1和2参数3
代码:实例化矩形(5,7)2
代码:实例化Rectangle()2
代码:矩形类定义实例变量2
代码:为每个实例变量2定义getter和setter
代码:矩形类包括面积和周长方法4
代码:矩形类继承自某个对象,即使它是对象2
代码:矩形类定义宽度和长度属性4
代码:矩形包含派生的只读实例变量2
代码:当python文件作为main 2执行时调用main
代码:矩形类定义了返回字符串4的getStats()方法
执行:打印矩形a:1
执行:打印区域:351
执行:打印周长:24 1
执行:打印矩形b:1
执行:打印宽度:101
执行:打印高度:201
执行:打印区域:200 1
执行:打印周长:60 1
40分
我得到这个代码的开始是:def main():
print "Rectangle a:"
a = Rectangle(5, 7)
print "area: %d" % a.area
print "perimeter: %d" % a.perimeter
print ""
print "Rectangle b:"
b = Rectangle()
b.width = 10
b.height = 20
print b.getStats()
我应该得到这个输出:Rectangle a:
area: 35
perimeter: 24
Rectangle b:
width: 10
height: 20
area: 200
perimeter: 60
我已经走了这么远,但是我不能用矩形B来打印宽度和高度?class Rectangle:
def __init__(self, width=0, height=0):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * self.height + 2 * self.width
def setWidth(self, width):
self.width = width
def setHeight(self, height):
self.height = height
def getStats(self):
return "area: %s\nperimeter: %s" % (self.area(), self.perimeter())
def main():
print ""
print "Rectangle a:"
a = Rectangle(5, 7)
print "area: %s" % a.area()
print "perimeter: %s" % a.perimeter()
print ""
print "Rectangle b:"
b = Rectangle()
b.width = 10
b.height = 20
print b.getStats()
print ""
main()
我正在获取此输出:Rectangle a:
area: 35
perimeter: 24
Rectangle b:
area: 200
perimeter: 60
Process finished with exit code 0