雪之下雪乃. 发表于 2020-3-20 22:16:32

Python 中遇到的难题6

class Rectangle:
    length =   float(input('长:'))
    width = float(input('宽:'))

    def setRect(self):
      print("打印长和宽")
      self.length = length
      self.width = width

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

    def getArea(self):
      returnself.length * self.width

k = Rectangle()


这段代码为什么调用后会出错啊


k.setRect()
打印长和宽
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
    k.setRect()
File "E:/Python .project/class 长和宽.py", line 7, in setRect
    self.length = length
NameError: name 'length' is not defined

qiuyouzhi 发表于 2020-3-20 22:19:23

你得先定义一个__init__方法,在那里头定义length什么的

乍惊乍喜 发表于 2020-3-20 22:43:14

class Rectangle:
       
        def __init__(self, length, width):
                self.length = length
                self.width = width
       
        def set_rect(self):
                print('长:{}'.format(self.length))
                print('宽: {}'.format(self.width))
               
        def get_rect(self):
                print("这个矩形的长是%.2f,宽是%.2f" % (self.length, self.width))
       
        def get_area(self):
                return self.length * self.width
               
        def main(self):
                self.get_rect()
                self.set_rect()
               

if __name__ == '__main__':
        length = float(input('长:'))
        width = float(input('宽:'))
        k = Rectangle(length, width)
        k.main()
页: [1]
查看完整版本: Python 中遇到的难题6