MST

星途 面试题库

面试题:Python条件测试在类方法中的应用

定义一个名为Rectangle的类,包含属性width和height。编写一个类方法is_square,用于判断该矩形是否为正方形(即width和height相等)。在主程序中创建Rectangle类的实例,调用is_square方法,并根据返回结果输出相应信息。请完整实现Python代码,包括类的定义、类方法的编写以及主程序部分。
43.2万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def is_square(self):
        return self.width == self.height


if __name__ == "__main__":
    rect1 = Rectangle(5, 5)
    rect2 = Rectangle(4, 6)
    if rect1.is_square():
        print("rect1是正方形")
    else:
        print("rect1不是正方形")
    if rect2.is_square():
        print("rect2是正方形")
    else:
        print("rect2不是正方形")