繁体   English   中英

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__不是在dir(a.say)或其父类中,而是在a.say中。 __closure__返回闭包元组。 这让我感到困惑。 谢谢。

我不知道Python中instancemethod类型的对象的内部实现,但我认为__getattr__是如何在实例方法对象中工作的

我的猜测是,当您说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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM