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

时间:2019-11-01 09:17:22

标签: python class oop

我不知道从这里去哪里。如果创建的矩形具有偶数区域,则在调用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()

3 个答案:

答案 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)

我认为您正在使用python 2.7!

检查此问题及其答案enter image description here