如何在需要参数的__init__中构造无参数对象(矩形)
我正在做一个作业,需要一个 Rectangle
类来计算给定的面积和周长。我们已经有了 main() 函数,需要在这个基础上进行开发。代码运行到 b = Rectangle()
的时候出现了问题,提示说需要传入正好 3 个参数。
这里是我的代码:
我该怎么做才能让第二个矩形正常工作,而不改变 main 函数呢?
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()
1 个回答
3
继续了解一下Python对“构造函数”默认参数的支持……大概是这样的:
def __init__(self, width = 0, height = 0)