46讲课后题
import pickleimport os
class MyDes:
def __init__(self,name):
self.name = name
def __get__(self,instance,owener):
return self.name
def __set__(self,instance,value):
file_open = open(self.name + '.pkl','wb' )
pickle.dump(self.name,file_open)
file_open.close()
self.name = value
def __delete__(self, instance):
file_open = open(self.name + '.pkl', 'wb')
file_content = pickle.load(file_open)
file_content.truncate(0)
os.remove(file_open)
file_open.close()
class Test:
x = MyDes('x')
y = MyDes('y')
test = Test()
test.x = 123
test.y = "I love FishC.com!"
print(test.x)
del test.x
错误信息TypeError: unsupported operand type(s) for +: 'int' and 'str'
应该怎么修改__delete__
数字类型和字符串类型不能直接拼接,要么都转换成字符串再拼接,要么先都转换为数字...... 本帖最后由 叙白 于 2022-3-25 20:18 编辑
str(self.name), 因为你__set__里改变了self.name的值,下面test.x = 123,将123赋值给了self.name
页:
[1]