
python中“can't set attribute”错误的解决
在python开发中,有时会遇到类似“can't set attribute”这样的错误。这种错误通常与属性的设置或访问相关。
你的代码片段中出现了以下问题:
- 属性名称不一致:你定义的属性是“gettest1”,但在尝试设置它时,却使用了“settest1”。属性名称应该保持一致。
- 代码缩进错误:你的代码中存在缩进错误。属性设置方法应该缩进为与属性声明方法相同级别。
- 使用不正确的属性装饰器:你使用了错误的属性装饰器。对于属性设置方法,应该使用@property.setter装饰器,而不仅仅是@property。
正确的代码应该如下:
立即学习“Python免费学习笔记(深入)”;
class Test2Class(object):
def __init__(self, name):
self.__name = name
@property
def name(self):
return self.__name
@name.setter
def name(self, name):
self.__name = name
@property
def now(self):
return time.time()
if __name__ == "__main__":
test2clas = Test2Class("w")
print(test2clas.name)
test2clas.name = 'wwwwee'
print(test2clas.name)
times = test2clas.now # 读取
print(str(times))通过修复这些问题,你的代码将能够正确运行,不会出现“can't set attribute”错误。










