简体   繁体   中英

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

In Python3, A.say is a function, and I know it has __closure__ attribute. __closure__ not in dir(a.say) or its super class, but a.say. __closure__ returns the closure tuple. It makes me confuse. Thanks.

I don't know in Python the internal implementation of objects with type instancemethod but I think it is how __getattr__ works in instance method objects .

My guess is when you say a.say.__closure__ it first looks up for __closure__ in dir(a.say) and then fallbacks on 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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