访问对象内存地址

2024-05-14 18:18:20 发布

您现在位置:Python中文网/ 问答频道 /正文

当您在Python中调用object.__repr__()方法时,会得到如下结果:

<__main__.Test object at 0x2aba1c0cf890> 

如果您重载了__repr__(),然后调用super(Class, obj).__repr__()并将其重新退出,是否有方法获得内存地址?


Tags: 方法testobjobjectmainatclasssuper
3条回答

您可以这样重新实现默认repr:

def __repr__(self):
    return '<%s.%s object at %s>' % (
        self.__class__.__module__,
        self.__class__.__name__,
        hex(id(self))
    )

只是使用

id(object)

关于id()Python manual可以这样说:

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. Two objects with non-overlapping lifetimes may have the same id() value. (Implementation note: this is the address of the object.)

所以在CPython中,这将是对象的地址。不过,对于其他任何Python解释器都没有这样的保证。

注意,如果您正在编写一个C扩展,那么您可以完全访问Python解释器的内部,包括直接访问对象的地址。

相关问题 更多 >

    热门问题