我不知道从这里去哪里。如果创建的矩形具有偶数区域,则在调用get_area
方法时将打印计算出的区域,并且num_rectangles
的值应增加1。
如果创建的矩形具有奇数个区域,则程序应返回一条消息,指出该区域不是偶数。
class Rectangle:
"""
This class represents a rectangle. It
has a length and a width and is capable
of computing its own area.
"""
def __init__(self, length = 0, width = 0):
"""
Initializes a rectangle with an optional
length and width.
"""
self.length = length
self.width = width
self.num_rectangles = num_rectangles +1
def __repr__(self):
"""
Returns a string representation of the
rectangle.
"""
return "rectangle with length: " + str(self.length) \
+ " and width: " + str(self.width)
def get_area(self):
"""Returns the rectangle's area."""
self.area = self.width * self.length
if (self.area %2) == 0:
return str(area)
r1 = Rectangle(2, 6)
print r1
print r1.get_area()
r2 = Rectangle(3, 5)
print r2
print r2.get_area()
答案 0 :(得分:0)
将num_rectangles
定义为类变量而不是实例变量,并在if-else
方法中使用get_area
:
class Rectangle:
num_rectangles = 0
def __init__(self, length = 0, width = 0):
self.length = length
self.width = width
# Rectangle.num_rectangles += 1
def __repr__(self):
"""
Returns a string representation of the
rectangle.
"""
return "rectangle with length: " + str(self.length) \
+ " and width: " + str(self.width)
def get_area(self):
"""Returns the rectangle's area."""
area = self.width * self.length
if (area %2) == 0:
Rectangle.num_rectangles += 1
return str(area)
else:
return "area is not an even value."
答案 1 :(得分:0)
class Rectangle:
__num_rectangles = 0
"""
This class represents a rectangle. It
has a length and a width and is capable
of computing its own area.
"""
def __init__(self, length = 0, width = 0):
"""
Initializes a rectangle with an optional
length and width.
"""
self.length = length
self.width = width
Rectangle.__num_rectangles += 1
def __repr__(self):
"""
Returns a string representation of the
rectangle.
"""
return "rectangle with length: " + str(self.length) \
+ " and width: " + str(self.width)
def get_area(self):
"""Returns the rectangle's area."""
self.area = self.width * self.length
if (self.area %2) == 0:
return str(self.area)
else:
print("Area isn't an even value")
r1 = Rectangle(2, 6)
print r1
r1.get_area()
print r1.get_area()
r2 = Rectangle(3, 5)
print r2
print r2.get_area()
答案 2 :(得分:-1)