18

Let's say I have a class

class A:
    def method(self):
        return self

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

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
Sahand
  • 7,980
  • 23
  • 69
  • 137

2 Answers2

18

It returns a reference:

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

You can think of it this way: You actually pass self to the .method() function as an argument and it returns the same self.

Selcuk
  • 57,004
  • 12
  • 102
  • 110
7

It returns a reference to the object, 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 the id function (from python docs):

Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime.

gonz
  • 5,226
  • 5
  • 39
  • 54
Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65