python绑定方法中的__closure__属性从何而来?

Where does the __closure__ attribute in python bound method come from?

# python3
def foo(a):
    class A:
        def say(self):
            print(a)
    return A
A = foo(1)
'__closure__' in dir(A.say) # True
a = A()
a.say.__closure__ # it returns the closure tuple
'__closure__' in dir(a.say) # False
'__closure__' in dir(a.say.__class__) # False
'__closure__' in dir(a.say.__class__.__class__) # False

在Python3中,A.say是一个函数,我知道它有__closure__属性。 __closure__ 不在目录 (a.say) 或其超级 class 中,而是 a.say.__closure__ returns 闭包元组。这让我很困惑。 谢谢

我不知道 Python 类型为 instancemethod 的对象的内部实现,但我认为这是 __getattr__ 的工作方式在 instance method objects

我的猜测是当你说 a.say.__closure__ 它首先在 dir(a.say) 中查找 __closure__ 然后回退到 dir(a.say.im_func).

>>> a = foo(1)()
>>> print type(a.say)
>>> instancemethod

>>> a.say.im_func.__closure__
>>> (<cell at 0x10a00f980: int object at 0x7fef29e098b8>,)

>>> '__closure__' in dir(a.say.im_func)
>>> True