|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
这是小甲鱼的课后练习题, 我有点不明白为什么在定义长宽的时候 要先给定一个初始值 length = 5 和 width = 4. 我自己改成了None, 也能跑出结果, 我已经把我不能理解的地方注释在代码中了。 求大佬为小萌新解答。。 先谢谢大佬们。
class Rectangle:
# 为什么这里要属性确定一个初始值?小甲鱼设置了4,5;我设置None也可以啊。
# 还有其他的初始化属性值的方法吗?
# length = 5
# width = 4
length=None
width = None
def setRect(self):
print('please enter the length and width to set a rectangle')
self.length=float(input('length:'))
self.width=float(input('width:'))
def getRect(self):
print('the length and width of this rectangle is: %.2f, %.2f, respectively' % (self.length, self.width))
def getArea(self):
print(self.length*self.width)
a = Rectangle()
a.setRect()
a.getRect()
a.getArea()
本帖最后由 Twilight6 于 2020-5-23 08:41 编辑
你是没有认真读懂题意,小甲鱼题目要求就是要达到图片这种效果:
和你用不用 None 替代无关,你初始值啥也可以替代,只要不影响这个类的需求功能即可
但是你设置 None 直接一开始就获取面积时肯定就会报错了 你可以试试把 a.getArea() 放在 a.setRect() a.getRect() 的前面
而你不初始化 length 和 width 就达不到初始时候实例对象就有长和宽,小伙子要认真读题啊~
|
|