Python“属性对象没有属性”异常

ost*_*ard 5 python django properties

confirmation = property(_get_confirmation, _set_confirmation)
confirmation.short_description = "Confirmation"
Run Code Online (Sandbox Code Playgroud)

当我尝试上述操作时,我得到一个异常,我不太明白:

AttributeError: 'property' object has no attribute 'short_description'
Run Code Online (Sandbox Code Playgroud)

这是对这里另一个问题的回答,但我无法对此发表评论,因为我没有足够的积分或其他东西。:-(

在其他测试中,我在类似情况下也遇到了此错误:

TypeError: 'property' object has only read-only attributes (assign to .short_description)
Run Code Online (Sandbox Code Playgroud)

有人有什么想法吗?

Aar*_*lla 2

property() 的结果是一个不能添加新字段或方法的对象。它是不可变的,这就是您收到错误的原因。

实现您想要的效果的一种方法是使用四个参数property()

confirmation  = property(_get_confirmation, _set_confirmation, None, "Confirmation.")
Run Code Online (Sandbox Code Playgroud)

或者将解释放入 的文档字符串中_get_confirmation

请参阅此处的文档,Python 2 也支持)

[编辑]至于答案您参考:我认为当您查看示例时,示例的缩进是完全错误的。现在这个问题已经解决了。