在Python中,“返回自我"是否返回对象或指针的副本? [英] In Python, does 'return self' return a copy of the object or a pointer?

查看:252
本文介绍了在Python中,“返回自我"是否返回对象或指针的副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我说一堂课

class A:
    def method(self):
        return self

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

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

推荐答案

它返回一个引用:

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

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

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

这篇关于在Python中,“返回自我"是否返回对象或指针的副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆