在Python中,'返回self'是否返回对象或指针的副本?

Sah*_*and 10 python pointers class

假设我有一堂课

class A:
    def method(self):
        return self
Run Code Online (Sandbox Code Playgroud)

如果method被调用,是指向A要返回的对象的指针,还是对象的副本?

Sel*_*cuk 11

它返回一个引用:

>>> a = A()
>>> id(a)
40190600L
>>> id(a.method())
40190600L
>>> a is a.method()
True
Run Code Online (Sandbox Code Playgroud)

你可以这样想:你实际上作为参数传递 self.method()函数,它返回相同的self.


AK4*_*K47 5

它返回一个对象的引用,看下面的例子:

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
Run Code Online (Sandbox Code Playgroud)

关于id函数(来自python 文档):

返回对象的“身份”。这是一个整数(或长整数),保证在此对象的生命周期内是唯一且恒定的。