|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
想增加删除属性的记录,在__delete__(self, instance)应该添加什么代码,现在del test.y删除不了。请各位大神指点下,谢谢了!
代码如下:
import time
class Record:
def __init__(self, obj = None, name = None, fdel = None):
self.obj = obj
self.name = name
self.fdel = fdel
self.file = r'C:\Users\WL-GL-001-01\Desktop\test.txt'
def __get__(self, instance, owner):
with open(self.file, 'a') as f:
f.writelines('{}于北京时间{}被读取,{}={}'.format(self.name, time.ctime(), self.name, self.obj)+'\n')
return self.obj
def __set__(self, instance, value):
self.obj = value
with open(self.file, 'a') as f:
f.writelines('{}于北京时间{}被修改,{}={}'.format(self.name, time.ctime(), self.name, self.obj) + '\n')
#添加删除记录
def __delete__(self, instance):
with open(self.file, 'a') as f:
f.writelines('{}于北京时间{}被删除,{}={}'.format(self.name, time.ctime(), self.name, self.obj) + '\n')
#这里应该补什么代码,才能删除test的属性,比如test.y
class Test:
x = Record(10, 'x')
y = Record(8.8, 'y')
test =Test()
print(test.x)
print(test.y)
test.x = 123
test.x = 1.23
test.y = 'I love FishC.com!'
del test.y
test.y
是我错了,这里就是描述符类 Record,确实是重写 __delete__
在 __delete__ 下加上 self.__dict__.pop('name') 即可,参考代码:
import time
class Record:
def __init__(self, obj = None, name = None, fdel = None):
self.obj = obj
self.name = name
self.fdel = fdel
self.file = r'C:\Users\WL-GL-001-01\Desktop\test.txt'
def __get__(self, instance, owner):
with open(self.file, 'a') as f:
f.writelines('{}于北京时间{}被读取,{}={}'.format(self.name, time.ctime(), self.name, self.obj)+'\n')
return self.obj
def __set__(self, instance, value):
self.obj = value
with open(self.file, 'a') as f:
f.writelines('{}于北京时间{}被修改,{}={}'.format(self.name, time.ctime(), self.name, self.obj) + '\n')
def __delete__(self, instance):
with open(self.file, 'a') as f:
f.writelines('{}于北京时间{}被删除,{}={}'.format(self.name, time.ctime(), self.name, self.obj) + '\n')
self.__dict__.pop('name')
|
|