如何在Python中的矩形实例之间使用比较属性

发布于 2025-02-10 11:21:16 字数 2205 浏览 2 评论 0原文

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'

我应该称任何功能吗?

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

tried to compare but got an error...

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

should I call any of the functions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

滥情哥ㄟ 2025-02-17 11:21:16
@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
@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
_畞蕅 2025-02-17 11:21:16

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

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无法比较ab,因为没有两个对象之间的比较标准。
因此,当我们考虑A大于B时,我们需要告诉解释器。

许多语言提供了定义比较的某种方法,例如==,!=,&lt;,&gt;。
在Python中,您可以定义当我们说a大于b的情况下,超压> gt 方法。

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")

在这里,我定义了,当我们考虑自我比其他更大时。
因此,解释器调用 gt 方法当我使用&gt;对于mylass的对象。

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

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

Imagine that you created new class without any methods, and compare two objects of the class.

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 cannot compare a and b, because there is no criteria for comparison between two objects.
So we need to tell the interpreter when we consider a is bigger than b.

Many languages provide some way to define comparisons, like ==, !=, <, >.
In Python, you can define when we say a is bigger than b with overriding gt method.

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")

Here, I defined when we consider self is bigger than other.
So interpreter call gt method when I use > for an object of Myclass.

If you want to consider rectangle is bigger than the other when width is bigger than other, you can write the code like

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

    ...

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文