我正在进行一项任务,该任务需要一个Rectangle
类来计算给定的面积和周长。我们已经获得了main()函数,并且必须围绕它构建。它似乎一直运行到b = Rectangle()
所在的地方
正好需要3个参数。
这是我的代码:
class Shape(object):
def __init__(self):
pass
def area():
pass
def perimeter():
pass
class Rectangle(Shape):
def __init__(self, width, height):
Shape.__init__(self)
self.width = width
self.height = height
def area(self):
area = self.height * self.width
return area
def perimeter(self):
perimeter = 2*(self.width+self.height)
return perimeter
def getStats():
print "Width: %d" % b.width
print "Height: %d" % b.height
print "Area: %d" % b.area
print "Perimeter: %d" % b.perimeter
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()
main()
如何在不更改主函数的情况下使第二个矩形工作?
答案 0 :(得分:3)
阅读python对default arguments对"构造函数的支持" ...类似
def __init__(self, width = 0, height = 0)