Big-Man 发表于 2019-9-21 10:01:27

getArea(self)为什么可以直接调用setRect(self)中的 length和width,而getRect(sel...

getArea(self)为什么可以直接调用setRect(self)中的 length和width,而getRect(self)中调用的是已经有的属性 length = 5,width = 4?



class Rectangle:
    length = 5
    width = 4
   
    def setRect(self):
      print("请输入矩形的长和宽...")
      self.length = float(input('长:'))
      self.width = float(input('宽:'))

    def getRect(self):
      print('这个矩形的长是:%.2f,宽是:%.2f' % (self.length, self.width))
      
    def getArea(self):
      return self.length * self.width

塔利班 发表于 2019-9-21 10:11:21

没使用setRect,长宽默认就是使用的类属性,self这里是指代实例化的对象
使用后,实例就有了实例属性

Big-Man 发表于 2019-9-21 10:16:06

塔利班 发表于 2019-9-21 10:11
没使用setRect,长宽默认就是使用的类属性,self这里是指代实例化的对象
使用后,实例就有了实例属性

明白了{:5_106:}

北轨 发表于 2020-4-6 21:47:37

本帖最后由 北轨 于 2020-4-6 21:55 编辑

页: [1]
查看完整版本: getArea(self)为什么可以直接调用setRect(self)中的 length和width,而getRect(sel...