首页 > 其他分享 >(面向对象)已知长方形类Rectangle,在构造方法中有私有实例变量宽__width和高__height,有area()方法用于求长方形的面积,请用@property装饰器定义属性width及其相应

(面向对象)已知长方形类Rectangle,在构造方法中有私有实例变量宽__width和高__height,有area()方法用于求长方形的面积,请用@property装饰器定义属性width及其相应

时间:2022-10-18 17:44:28浏览次数:38  
标签:__ .__ 未定义 r2 height width def

样例输入

3 4

 

样例输出

3*4=12
4*5=20
未定义宽,未定义高

 

样例输入

6 7

 

样例输出

6*7=42
7*8=56
未定义宽,未定义高

 

解题代码

#coding=gbk
class Rectangle:  #定义长方形类
    """【"""
    @property
    def width(this):
        return this.__width
    @width.setter
    def width(this,width):
        this.__width=width
    @width.deleter
    def width(this):
        del this.__width
    @property
    def height(this):
        return this.__height
    @height.setter
    def height(this,height):
        this.__height=height
    @height.deleter
    def height(this):
        del this.__height
    """】"""
    def area(self):  #定义计算面积的方法area()
        return self.__width * self.__height  #按设置的宽、高计算面积
    def __init__(self, width=0, height=0):   #定义构造方法
        self.__width = width  #创建实例变量,宽
        self.__height = height  #创建实例变量,高
a,b=map(int,input().split())
r1=Rectangle(a,b)
print('{}*{}={}'.format(r1.width,r1.height,r1.area()))  #计算面积
r2=Rectangle()  #创建对象,用默认值初始化实例
r2.width=a+1  #设置宽
r2.height=b+1  #设置高
print('{}*{}={}'.format(r2.width,r2.height,r2.area()))  #计算面积
del r2.width
try:
    print(r2.width,end='')
except:
    print('未定义宽,',end='')
del r2.height
try:
    print(r2.height)
except:
    print('未定义高')

 

标签:__,.__,未定义,r2,height,width,def
From: https://www.cnblogs.com/hghdbk/p/16803438.html

相关文章