python / python/cpython

Assigning attribute to instance method causes AttributeError

未關閉
#100,057 8 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

interpreter-core type-bug
主要語言
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

貢獻指南

開啟貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

研究方向

首先,在受影響的 Python 版本中重現 issue 裡的實例方法屬性指派範例。在決定是否應支援指派或釐清錯誤之前,檢查方法屬性和描述器的行為;完成標準是確定一致的行為並提供相應的回歸涵蓋範圍。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
python
領域
backend
Issue 類型
缺陷
難度
5/5
預估耗時
一週以上
活躍度
停滯
描述清晰度
需要釐清
新手友好度
25/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。