In Python, "returns self" returns a copy of an object or pointer?

Say I have a class

class A: def method(self): return self 

If method is called, is the pointer to the returned object A or a copy of the object?

+6
source share
2 answers

It returns a link:

 >>> a = A() >>> id(a) 40190600L >>> id(a.method()) 40190600L >>> a is a.method() True 

You can think of it this way: you are actually passing self to the .method() function as an argument and returning the same self .

+6
source

It returns an object reference, look at the following example:

 class A: def method(self): return self a = A() print id(a.method()) print id(a) > 36098936 > 36098936 b = a.method() print id(b) > 36098936 

About id function (from python docs ):

Return the "identifier" of the object. This is an integer (or long integer) that is guaranteed to be unique and constant for this object during its lifetime.

+2
source

All Articles