这样啊812 2022-01-17 23:28 采纳率: 70%
浏览 21
已结题

面向对象中的属性——方法变属性

为什么这里出错了?

img


img

  • 写回答

1条回答 默认 最新

  • 关注

    img

    @property  
    def area(self):
        return self.width*self.height
    

    多了一层缩进,成了 def init() 的子函数

    class Rect():
        def __init__(self,width,height):
            self.width = width
            self.height = height
    
        # 这个要减少一层缩进放在def __init__函数之外
        @property
        def area(self):
            return self.width*self.height
    
    rect = Rect(800,600)
    print(rect.area)
    
    

    如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 1月26日
  • 已采纳回答 1月18日
  • 修改了问题 1月17日
  • 创建了问题 1月17日