|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 xiaofan1228 于 2020-3-8 14:58 编辑
题目
- >>> class Test:
- x = MyDes(10, 'x')
- >>> test = Test()
- >>> y = test.x
- 正在获取变量: x
- >>> y
- 10
- >>> test.x = 8
- 正在修改变量: x
- >>> del test.x
- 正在删除变量: x
- 噢~这个变量没法删除~
- >>> test.x
- 正在获取变量: x
- 8
复制代码
答案
- class MyDes:
- def __init__(self, initval=None, name=None):
- self.val = initval
- self.name = name
- def __get__(self, instance, owner):
- print("正在获取变量:", self.name)
- return self.val
- def __set__(self, instance, value):
- print("正在修改变量:", self.name)
- self.val = value
- def __delete__(self, instance):
- print("正在删除变量:", self.name)
- print("噢~这个变量没法删除~")
复制代码
[b]
我的问题是,
为什么在上述题目中,delete方法没有办法删除变量x??
另:
“必须把描述符定义成另外一个类触发的类属性,不能定义到构造函数。”
这句话该怎么理解呢?
[/b]
1. 因为在 MyDes 中的 __delete__ 方法没有写删除 x 的语句,所以 x 一直存在。
2. 就是必须在类中,但不能在函数中定义。
比如,这是正确的:
- class Test:
- x = MyDes(10, 'x')
复制代码
这是错误的:
- class Test:
- def __init__(self):
- self.x = MyDes(10, 'x')
复制代码
|
|