Method related python code behavior

I am a little confused about what is going on in the python interpreter for these code snippets ... I am using the 32-bit version of python 2.7.3

class A: def func(self): print 'in func' >>> A.func >>> <unbound method Af> >>> A.__dict__['func'] >>> <function func at 0x013DF9B0> >>> a = A() >>> a.func >>> <bound method A.func of <__main__.A instance at 0x014076C0>> 

So far, everything is fine ... But I am confused by the results of the following code snippets ... in python 2.7.3

(1)

 >>> A.__dict__['func'] is A.func >>> False >>> A.func is A.func >>> False >>> a.func is A.func >>> False >>> a.func is a.func >>> False 

why everything returns False, although there is only one object of class (A) and one instance of an object of type class (a).

(2)

 >>> id(A.func) >>> 20953208 >>> id(A.func) >>> 20954728 >>> id(A.func) >>> 20960080 

(3)

 >>> id(a.func) >>> 20954288 >>> id(a.func) >>> 20952888 >>> id(a.func) >>> 20954728 

for (2) and (3) why it changes the identifier again and again ... this function is not stored in the specified memory location.

But the same code for block (1) gives this result in 32-bit version of python 3.3.1

 >>> A.__dict__['func'] is A.func >>> True >>> A.func is A.func >>> False >>> a.func is A.func >>> False >>> a.func is a.func >>> False 

Can someone tell me details about how these results will be different for different versions of python, and why this happens in the same version of python too ...

+4
source share
1 answer

you need to compare the base function. method is not a function.

 >>> A.func.__func__ is A.func.__func__ True 

this is because python adds a wrapper around functions (and doesn’t seem to cache them - a new one is created every time a method is requested) to do the extra magic necessary for self work correctly in methods. I'm trying to remember what it's called. part of the explanation is at http://docs.python.org/2.6/reference/datamodel.html (scroll down to "User Defined Methods"), but I'm sure the explanation is better there.

additional snippets at http://docs.python.org/2.6/tutorial/classes.html#method-objects http://docs.python.org/2.6/c-api/method.html#method-objects and http: //docs.python.org/2.6/library/stdtypes.html#methods

We hope that someone who knows more than me will publish (I answer because it is quite old and I thought I could point you in the right general direction).

+2
source

Source: https://habr.com/ru/post/1489063/


All Articles