|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import time
class Record:
def __init__(self, initval=None, name=None):
self.val = initval
self.name = name
self.filename = "record.txt"
def __get__(self, instance, owner):
with open(self.filename, 'a', encoding='utf-8') as f:
f.write("%s 变量于北京时间 %s 被读取,%s = %s\n" % \
(self.name, time.ctime(), self.name, str(self.val)))
return self.val
def __set__(self, instance, value):
filename = "%s_record.txt" % self.name #这里定义filemname的作用
with open(self.filename, 'a', encoding='utf-8') as f:
f.write("%s 变量于北京时间 %s 被修改, %s = %s\n" % \
(self.name, time.ctime(), self.name, str(value)))
self.val = value
问题:__set__中再次定义filename的作用?
__set__中文件写入调用的文件名self.filename应当还是一开始定义的‘record.txt’吧,然后以‘a’的方式在最后继续写入。这样filename的定义就没有用了啊
hm...这题我刚做完,感觉是没什么用,理论上应该是在一个record.txt里完成多个变量的记录工作,不存在多个变量分多个文件的情况。
之前没注意答案,一对比才发现我是个直接贴路径的粗人。。。 import time as t
import os
class Record:
def __init__(self, value, name):
self.value = value
self.name = name
def __get__(self, instance, owner):
with open("E:\\Python_homework\\46\\record.txt", 'a') as f:
f.writelines("Variable %s was read at %s, %s = %s \n" %(self.name, t.asctime(), self.name, self.value))
return self.value
def __set__(self, instance, value):
self.value = value
with open("E:\\Python_homework\\46\\record.txt", 'a') as f:
f.writelines("Variable %s was modified at %s, %s = %s \n" %(self.name, t.asctime(), self.name, self.value))
def __delete__(self, instance):
del self.value
class Test:
x = Record(10, 'x')
y = Record(8.8, 'y')
|
|