鱼C论坛

 找回密码
 立即注册
查看: 982|回复: 1

求解46讲描述符问题最后一题

[复制链接]
发表于 2018-4-19 11:50:02 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
import time as t
import pickle as p
import os


class MyDes:
    data = ''

    def __init__(self, cha=None):
        self.cha = cha

    def __get__(self, instance, owner):
        return self.value

    def __set__(self, instance, value):
        self.value = value
        file = open(self.cha + '.xpl', 'wb')
        p.dump(self.value, file)
        file.close()

    def __delete__(self, instance):
        os.remove(self.cha + '.xpl')
        super().__delattr__(self.cha)
        print(' delete confirm')


class Test:
    x = MyDes('x')


运行
test=Test()
test.x=123
del test.x

最后del test.x 后报错。。。说AttributeError: x
好奇怪为什么。。。
捕获.JPG
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2018-4-23 22:13:28 | 显示全部楼层
self成员变量要在__init__方法中初始化,该方法在对象创建时调用,如果写在其它方法中对象创建后可能还没有被加载。
可以用dir()函数进行验证:
>>> class Demo:
        def __init__(self, value):
                self.value = value
        def a():
                return self.var
        def b(var):
                self.var = var

               
>>> d = Demo(1)
>>> dir(d)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b', 'value']
>>>
可以看到,d对象是没有var属性的
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-12-29 13:18

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表