In Python, does 'return self' return a copy of the object or a pointer?

后端 未结 2 1397
太阳男子
太阳男子 2021-02-19 21:05

Let\'s say I have a class

class A:
    def method(self):
        return self

If method is called, is a pointer to the A

2条回答
  •  深忆病人
    2021-02-19 21:54

    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.

提交回复
热议问题