鱼C论坛

 找回密码
 立即注册
查看: 1549|回复: 2

Python 中遇到的难题6

[复制链接]
发表于 2020-3-20 22:16:32 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
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):
        return  self.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

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-3-20 22:19:23 | 显示全部楼层
你得先定义一个__init__方法,在那里头定义length什么的
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-3-20 22:43:14 | 显示全部楼层
  1. class Rectangle:
  2.        
  3.         def __init__(self, length, width):
  4.                 self.length = length
  5.                 self.width = width
  6.        
  7.         def set_rect(self):
  8.                 print('长:{}'.format(self.length))
  9.                 print('宽: {}'.format(self.width))
  10.                
  11.         def get_rect(self):
  12.                 print("这个矩形的长是%.2f,宽是%.2f" % (self.length, self.width))
  13.        
  14.         def get_area(self):
  15.                 return self.length * self.width
  16.                
  17.         def main(self):
  18.                 self.get_rect()
  19.                 self.set_rect()
  20.                

  21. if __name__ == '__main__':
  22.         length = float(input('长:'))
  23.         width = float(input('宽:'))
  24.         k = Rectangle(length, width)
  25.         k.main()
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-15 01:14

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表