通過屬性求面積

需求:
1. 寫一個矩形類,默認有寬和高兩個屬性;
2. 如果爲一個叫square的屬性賦值,那麼說明這是一個正方形,值就是正方形的邊長,此時寬和高都應該等於邊長。

class Rectangle:
    def __init__(self,width=0,height=0):
        self.width = width
        self.height = height

    def __setattr__(self, key, value):
        if key == "square":
            self.width = value
            self.height = value
        else:
            self.__dict__[name]=value         #方法1:使用實例的字典屬性
            #super().__setattr__(key,value)   #方法2:調用基類方法
    def getArea(self):
        return self.width * self.width

>>>r1=Rectangle(4,5)
>>>r1.getArea()
16
>>>r1.square = 10
>>>r1.getArea()
100
>>>r1.__dict__
{'width': 10, 'height': 10}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章