|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 Tigeroad 于 2020-5-28 13:37 编辑
题目:1. 按要求编写描述符 :记录指定变量的读取和写入操作,并将记录以及触发时间保存到文件:record.txt。
在看小甲鱼老师的答案之前,我的代码是这么写的:
- import time as t
- class Record:
- def __init__(self, value, name):
- self.name = name
- self.value = value
- def __get__(self, instance, owner):#__get__可以成功调用
- print('getting...')#测试。__get__可以成功调用
- time = t.localtime()
- #写入文档,用的甲鱼老师课上讲的那个函数,代码有点蠢萌。。
- f = open('record.txt', 'a')
- temp = (self.name + '变量于北京时间 ')
-
- for i in range(6):
- temp += (str(time[i]) + ' ')
- temp += ('被读取, ' + self.name + ' = ' + str(self.value) + ' \n')
- f.writelines(temp)
- f.close()
-
- return self.value
- #以下无法调用,求解
- def __set__(self, instance, value):
- print('setting.....')#测试。__set__无法调用
- time = t.localtime()
- #写入文档,用的甲鱼老师课上讲的那个函数,代码有点蠢萌。。
- f = open('record.txt', 'a')
- temp = (self.name + '变量于北京时间 ')
- for i in range(6):
- temp += (str(time[i]) + ' ')
- temp += ('被修改, ' + self.name + ' = ' + str(self.value) + ' \n')
- f.writelines(temp)
- f.close()
-
- self.value = value
- class Test:
- x = Record(10, 'x')
- y = Record(8.8, 'y')
- test = Test
复制代码
运行之后IDLE显示如下:
- >>> test.x
- getting...
- 10
- >>> test.y
- getting...
- 8.8
- >>> test.x = 123
- >>> test.y = 234
- >>> test.y = 'i love you!'
复制代码
也就是__get__方法成功调用了, __set__方法没有调用,在record.txt文档中也是同样的结果,只有这两行:
x变量于北京时间 2020 5 28 13 26 59 被读取, x = 10
y变量于北京时间 2020 5 28 13 27 3 被读取, y = 8.8
想了一天了还是不知道哪里出了问题,请问大家哪里出了问题呢?非常感谢!
|
|