Assigning attribute to instance method causes AttributeError
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 77.2k
- 派生
- 36k
- PR 合并指标
- PR 指标待抓取
描述
Bug report
Assigning (and reassigning) attributes to functions works as expected as with any object.
def bar(self):
...
bar.something = 1
print(bar.something)
# prints: 1
bar.something = 2
print(bar.something)
# prints: 2
However, the experience is not consistent with class methods. When dealing with the class, you can assign and reassign similar to regular functions.
class Foo:
def bar(self):
...
Foo.bar.something = 1
print(Foo.bar.something)
# prints: 1
Foo.bar.something = 2
print(Foo.bar.something)
# prints: 2
This even carries through after instantiation:
foo = Foo()
print(foo.bar.something)
# prints: 2
We can clearly see the value exists in the __dict__:
print(foo.bar.__dict__)
# {'something': 2}
However, trying to assign to the method from the instance fails:
foo.bar.something = 2
# AttributeError: 'method' object has no attribute 'something'
While I guess I can see why this might be (since you would be modifying an object on the class and not the instance--if this indeed is the rationale), this is not intuitive. It seems inconsistent with setting attributes otherwise.
If this behavior is intended and not a bug, then perhaps the error should be more explicit. The error stating that the method has no attribute named something is not correct. It does have the attribute and we can otherwise interact with it, just not set it.
Either we should be able to assign back to that attribute from the instance, or we should receive a more explicit error why this is not possible.
Your environment
- CPython versions tested on: 3.7.12, 3.8.11, 3.9.9, 3.10.8, 3.11.0rc1
- Operating system and architecture:
▶ uname -a
Linux hopkins 6.0.2-arch1-1 #1 SMP PREEMPT_DYNAMIC Sat, 15 Oct 2022 14:00:49 +0000 x86_64 GNU/Linux
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
首先,在受影响的 Python 版本中重现 issue 里的实例方法属性赋值示例。在决定是否应支持赋值或明确错误之前,检查方法属性和描述符的行为;完成标准是确定一致的行为并提供相应的回归覆盖。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- backend
- Issue 类型
- 缺陷
- 难度
- 5/5
- 预计耗时
- 一周以上
- 活跃度
- 停滞
- 描述清晰度
- 需要澄清
- 新手友好度
- 25/100