我如何制作一个仅跟踪在python中具有偶数区域的矩形的变量

问题描述 投票:0回答:1

我不知道从这里去哪里。如果创建的矩形具有偶数区域,则在调用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()
python class oop object rectangles
1个回答
0
投票

num_rectangle定义为类变量而不是实例变量,并在if-else方法中使用get_area

class Rectangle:
    num_rectangle = 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:
            return str(area) 
        else:
            print("area is not an even value.")
© www.soinside.com 2019 - 2024. All rights reserved.