麦子学院——Python面向对象编程(P7深入类的属性)

本文通过Python类的属性包装器与描述符实现私有属性的读写控制及类属性的有效验证,同时展示了如何定义_call_方法以实现类实例作为函数调用的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

修改上节课的作业中定义的类:
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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值