麦子学院——Python面向对象编程(P6让对象具有能动性)

江枫思渺然 提交于 2019-12-25 11:46:07

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

    def set_color(self, color):
        self.__color=color

    def open(self):
        if self.__disclosure == False:
            self.__disclosure = True
            print("the box has been opened!")
        else:
            print("repeated opening unpermitted!")

    def close(self):
        if self.__disclosure == True:
            self.__disclosure = False
            print("the box has been closed!")
        else:
            print("repeated closing unpermitted!")

测试

if __name__ == '__main__':
    a = Box(1, 2, 3,"red")
    print(a.get_color())    # red
    a.set_color("black")
    print(a.get_color())    # black
    a.open()    #the box has been opened!
    a.open()    #repeated opening unpermitted!
    a.close()   #the box has been closed!
    a.close()   #repeated closeing unpermitted!
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!