|
楼主 |
发表于 2022-4-22 19:55:58
|
显示全部楼层
'''
0. 将拥有特殊方法(包括get, set ,delete)的类的实例 定义给其他类的属性,这个属性称之为描述符
1. __get__ (self, inst ,owner), __set__ (self , inst , value ), __delete__ (self, inst)
2. test.a
3. 0 , 先init , set , get
4. 9
'''
#动动手2
#动动手1
from pathlib import Path as p
import time as t
class Record:
#初始化键值对,对应的变量 与值利用字典的属性链接起来
def __init__(self, value = 0 , name = ''):
self.dictt = {}
self.name = name
self.dictt[self.name] = value
#访问属性
def __get__(self, inst , owner):
self.time = t.ctime()
self.recordFile()
return self.dictt[self.name]
#更改属性值
def __set__(self, inst , value):
self.time = t.ctime()
self.dictt[self.name] = value
self.recordFile()
#生成保存日志
def recordFile(self):
with open(r'C:/Users/zhuzj/Desktop/python/test/老教材/record.txt','a+') as self.file:
self.words = f' {self.name} 变量于北京时间 {self.time}被读取, {self.name} = {self.dictt[self.name]}\n '
self.file.write(self.words)
class Test:
x = Record(10, 'x')
y = Record(8.8, 'y')
test = Test()
test.x
test.y
test.x = 123
test.x = 1.23
test.y = 'i love fishc'
#动动手0
class MyDes:
def __init__(self, value = 0 , name = ''):
self.dictt = {}
self.value = value
self.name = name
self.dictt[self.name] = self.value
def __get__(self, inst , owner):
print(f'正在获取变量:{self.name}')
return self.dictt[self.name]
def __set__(self, inst , value):
print(f'正在修改变量:{self.name}')
self.dictt[self.name] = value
def __delete__(self , inst):
print(f'正在删除变量:{self.name}\n哦这个变量没法删除 ')
class Test:
x = MyDes(10 , 'x')
test = Test()
test.x
|
|