|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- class rectangle:
- w = 5
- h = 4
- def __int__(self , w , h):
- self.w = w
- self.h = h
- def setrect(self):
- self.w = int(input('长:'))
- self.h = int(input('宽:'))
- def getrect(self):
- print('长宽分别为:', self.w , self.h)
- def getarea(self):
- return self.w * self.h
- rect = rectangle()
- rect.getarea()
复制代码
运行为空,没返回值
另外主要问一下,下面这段代码是否多余并且重复了? 如果是的话该如何改进下次避免?
- def __int__(self , w , h):
- self.w = w
- self.h = h
复制代码
1. 不应该是 __int__ ,而是 __init__ 。
2. 明明在第 2、3 行已经给 w 和 h 赋值了,为什么要在 __init__ 中再次赋值了?如果想设置默认值的话,可以使用函数的默认参数。
3. 最后一行中,虽然你调用了这个函数,但是你并没有将他的返回值打印出来,所以你没有看到任何回应。
改完的代码: - class rectangle:
- def __init__(self , w=5 , h=4): #如果没有传入参数,w 和 h 的默认值将会是 5 和 4
- self.w = w
- self.h = h
- def setrect(self):
- self.w = int(input('长:'))
- self.h = int(input('宽:'))
- def getrect(self):
- print('长宽分别为:', self.w , self.h)
- def getarea(self):
- return self.w * self.h
- rect = rectangle()
- print(rect.getarea())
复制代码
|
|