麦子学院——Python面向对象编程(P6让对象具有能动性)
P6让对象具有能动性 题目:修改P5中定义的类Box,要求其具有:访问私有属性(体积)的方法;添加颜色属性(__color)和设置与获取Box的颜色的方法;添加打开和关闭盒子(Box)的方法,并且限制Box打开(关闭)之后,再次调用打开(关闭)方法会给予提示:即不能重复打开与关闭,在主程序中实例化并进行测试。 答案: class Box : # Box类 instanceNum = 0 # 实例数 def __init__ ( self , length = 0 , width = 0 , height = 0 , color = None ) : self . length = length # 长 self . width = width # 宽 self . height = height # 高 self . __volume = self . length * self . height * self . width # 体积 Box . instanceNum += 1 self . __color = color #颜色 self . __disclosure = False def get_volume ( self ) : return self . __volume def get_color ( self ) : return self . __color