题目
修改上节课的作业中定义的类:
1、使用属性包装器将私有属性__color包装为color(可读写)属性
2、运用描述符在Box类中创建一个类属性(盒子六面的图案字符,只能为数字1-6)
3、为其定义_call_(),当作为函数调用时,返回其体积。
答案
class Pattern: #图案描述符
def __init__(self, default=1):
self.figure = default
def __get__(self, instance, owner):
return self.figure
def __set__(self, instance, val):
if val >= 1 and val <= 6:
self.figure = val
else:
print("value is supposed to be within 1~6!")
def __delete__(self, instance):
pass
class Box: # Box类
pattern = Pattern() #图案
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 __call__(self, *args, **kwargs): #返回体积
return self.__volume
@property
def color(self):
return self.__color
@color.setter
def 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.color) #red
a.color="yellow"
print(a.color) #yellow
print(a.pattern) #1
a.pattern = 3
print(a.pattern) #3
a.pattern = 100 #value is supposed to be within 1~6!
print(a()) #6