访问对象内存地址 [英] Accessing Object Memory Address

查看:46
本文介绍了访问对象内存地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当你在 Python 中调用 object.__repr__() 方法时,你会得到这样的返回:

<块引用>

<__main__.Test object at 0x2aba1c0cf890>

如果重载__repr__(),有没有办法获得内存地址,然后调用super(Class, obj).__repr__() 和正则表达式?

解决方案

Python手册id()有这样的说法:

<块引用>

返回对象的身份".这是一个整数(或长整数)保证是独一无二的此对象在其期间的常量寿命.两个对象不重叠的生命周期可能有相同的 id() 值.(实施注意事项:这是对象的地址.)

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

请注意,如果您正在编写 C 扩展,则您可以完全访问 Python 解释器的内部结构,包括直接访问对象的地址.

When you call the object.__repr__() method in Python you get something like this back:

<__main__.Test object at 0x2aba1c0cf890> 

Is there any way to get a hold of the memory address if you overload __repr__(), other then calling super(Class, obj).__repr__() and regexing it out?

解决方案

The Python manual has this to say about id():

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.)

So in CPython, this will be the address of the object. No such guarantee for any other Python interpreter, though.

Note that if you're writing a C extension, you have full access to the internals of the Python interpreter, including access to the addresses of objects directly.

这篇关于访问对象内存地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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