如何在 python 中 Rectangle 实例之间的静态方法中使用 comparison 属性

how to use the comparison attribute in a static method between instances of a Rectangle in python

提问人:Zebby 提问时间:6/27/2022 最后编辑:cardsZebby 更新时间:7/4/2023 访问量:268

问:

class Rectangle:
    """created a class Rectangles, assigning values"""
    number_of_instances = 0
    print_symbol = "#"

    def __init__(self, width=0, height=0):
        self.height = height
        self.width = width
        Rectangle.number_of_instances += 1

    @property
    def width(self):
        return self.__width

    @width.setter
    def width(self, value):
        if not isinstance(value, int):
            raise TypeError("width must be an integer")
        elif value < 0:
            raise ValueError("width must be >= 0")

        self.__width = value

    @property
    def height(self):
        return self.__height

    @height.setter
    def height(self, value):
        if not isinstance(value, int):
            raise TypeError("height must be an integer")
        elif value < 0:
            raise ValueError("height must be >= 0")

        self.__height = value

    def area(self):
        return self.__height * self.__width

    def perimeter(self):
        if self.__height == 0 or self.__width == 0:
            return 0
        return (self.__height + self.__width) * 2

    def __str__(self):
        if self.__width == 0 or self.__height == 0:
            return ''
        for z in range(self.height - 1):
            print(str(self.print_symbol) * self.__width)
        return str(self.print_symbol * self.__width)

    def __repr__(self):
        return "Rectangle({}, {})".format(self.__width, self.__height)

    def __del__(self):
        print("Bye rectangle...")
        Rectangle.number_of_instances -= 1

    @staticmethod
    def bigger_or_equal(rect_1, rect_2):
        if not isinstance(rect_2, Rectangle):
            raise TypeError("rect_2 must be an instance of Rectangle")
        elif not isinstance(rect_1, Rectangle):
            raise TypeError("rect_1 must be an instance of Rectangle")
        elif rect_1 == rect_2:
            return rect_1
        elif rect_1 > rect_2:
            return rect_1
        elif rect_2 > rect_1:
            return rect_2

尝试比较但出现错误...

TypeError: '>' not supported between instances of 'Rectangle' and 'Rectangle'

我应该调用任何函数吗?

Python 方法 静态 比较 实例

评论

0赞 Carl HR 6/27/2022
该类来自哪个模块?Rectangle
0赞 Community 6/27/2022
请提供足够的代码,以便其他人可以更好地理解或重现问题。
1赞 Carl HR 6/27/2022
无论哪种情况,都可以通过创建一个继承自 .然后,在此类中,尝试实现 或 如此处所述:stackoverflow.com/questions/5824382/...RectangleRectangle__gt__()__eq__()
0赞 Zebby 6/27/2022
错误出在静态方法上

答:

-1赞 Taewoo Kim 6/27/2022 #1

假设您在没有任何方法的情况下创建了新类,并比较了该类的两个对象。

class MyClass:
    pass

if __name__ == '__main__':
    a = MyClass()
    b = MyClass()
    if a > b:
        print("a is bigger than b")
    else:
        print("a is not bigger than b")

Python 无法比较 和 ,因为两个对象之间没有比较的标准。 因此,当我们考虑时,我们需要告诉口译员。aba is bigger than b

许多语言都提供了一些定义比较的方法,例如 ==、!=、< >。
在 Python 中,您可以使用覆盖 gt 方法定义我们何时说。
a is bigger than b

class MyClass:
    def __init__(self, val1: int, val2: int):
        self.val1 = val1
        self.val2 = val2

    def __gt__(self, other):
        if isinstance(other, MyClass):
            return self.val1 * self.val2 > other.val1 * other.val2
        else:
            raise Exception("cannot compare(>) MyClass and {}".format(type(other)))


if __name__ == '__main__':
    a = MyClass(1, 5)
    b = MyClass(2, 3)
    if a > b:
        print("a is bigger than b")
    else:
        print("a is not bigger than b")

在这里,我定义了. 因此,当我将 > 用于 Myclass 的对象时,解释器会调用 gt 方法。when we consider self is bigger than other

如果想在宽度大于其他矩形时考虑矩形比另一个矩形大,则可以编写如下代码

class Rectangle:
    """created a class Rectangles, assigning values"""
    number_of_instances = 0
    print_symbol = "#"

    def __init__(self, width=0, height=0):
        self.height = height
        self.width = width
        Rectangle.number_of_instances += 1

    def __gt__(self, other):
        if isinstance(other, Rectangle):
            return self.width > other.width
        else:
            raise Exception("cannot compare(>) Rectangle and {}".format(type(other)))

    ...

查看 https://docs.python.org/3/library/operator.html#operator

0赞 Ando Abza 7/4/2023 #2
@staticmethod
def bigger_or_equal(rect_1, rect_2):

   if not isinstance(rect_1, Rectangle):
      raise TypeError("rect_1 must be an instance of Rectangle")

   elif not isinstance(rect_2, Rectangle):
      raise TypeError("rect_2 must be an instance of Rectangle")

   elif rect_1.area() == rect_2.area():
       return rect_1

   if rect_1.area() >= rect_2.area():
       return rect_1

   else:
       return rect_2

评论

0赞 Community 7/6/2023
您的答案可以通过其他支持信息进行改进。请编辑以添加更多详细信息,例如引文或文档,以便其他人可以确认您的答案是正确的。您可以在帮助中心找到有关如何写出好答案的更多信息。