Как сделать переменную, которая отслеживает только прямоугольники, которые имеют четную область в Python - PullRequest
0 голосов
/ 01 ноября 2019

Я не знаю, куда идти отсюда. Если прямоугольник создается с четной областью, вычисленная область должна печататься при вызове метода 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()

Ответы [ 2 ]

0 голосов
/ 01 ноября 2019

Я думаю, что вы работаете с Python 2.7!

проверьте этот вопрос и его ответы Создание класса Rectangle

0 голосов
/ 01 ноября 2019

Определите 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."
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...