课堂笔记:
1. 文件打开用with open(path) as f 不用f.close(),方便
测试题:
0.
描述符是一个至少有__get__(self,instance,owner),__set__(self,instance,value),__delete__(self,instance)其一的类,并把这个类的实例对象赋予其他类的属性,被赋予属性的类就被描述符描述了.
一个程序有一个需求,在变量被查找赋值或删除时执行,就用描述符来完成.
1.
get:__get__(self,instance,owner),
set:__set__(self,instance,value),
del:__delete__(self,instance)
2.
都会
3.
20
0
4.
9
返回实例层次的描述符,会返回描述符本身,必须调用类层次的描述符,否则无法调用set,get等方法.
动动手:
0.
class MyDes:
def __init__(self,value = 0,name = '未命名'):
self.value = value
self.name = name
def __get__(self,instance,owner):
print('正在获取变量:',self.name)
return self.value
def __set__(self,instance,value):
print('正在修改变量:',self.name)
self.value = value
def __delete__(self,instance):
print('正在删除变量:',self.name)
print('噢,这个变量没法删除~')
class Test:
x = MyDes(10,'x')
test = Test()
1.
i self.name = name
def __get__(self,instance,owner):
print('%s 变量于北京时间 %s 被读取,%s = ' % (self.name,t.asctime(),self.name),self.value)
get_record = '%s 变量于北京时间 %s 被读取,%s = ' % (self.name,t.asctime(),self.name) + str(self.value) + '\n'
f = open('/Users/yufan/Documents/python编程/46/46dds1_record.txt','a',encoding = 'GBK')
f.write(get_record)
f.close()
return self.value
def __set__(self,instance,value):
self.value = value
print('%s 变量于北京时间 %s 被修改,%s = ' % (self.name,t.asctime(),self.name),self.value)
set_record = '%s 变量于北京时间 %s 被修改,%s = ' % (self.name,t.asctime(),self.name) + str(self.value) + '\n'
f = open('/Users/yufan/Documents/python编程/46/46dds1_record.txt','a',encoding = 'GBK')
f.write(set_record)
f.close()
class Test:
x = Record(10,'x')
y = Record(8.8,'y')
test = Test()
2.
import pickle as p
import os
class MyDes:
def __init__(self,name = '未命名',value = 0):
self.name = name
self.value = value
def __get__(self,instance,owner):
return self.value
def __set__(self,instance,value):
self.value = value
set_file = open('/Users/yufan/Documents/python编程/46/46dds2/%s.pkl' % self.name,'wb')
p.dump(self.value,set_file)
set_file.close()
def __delete__(self,instance):
os.remove('/Users/yufan/Documents/python编程/46/46dds2/%s.pkl' % self.name)
class Test:
x = MyDes('x')
y = MyDes('y')
test = Test()