推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
uwh0am1
V2EX  ›  Python

Python 如何从内存地址上加载 pythn 对象

  •  
  •   uwh0am1 · Jul 27, 2018 · 3280 views
    This topic created in 2868 days ago, the information mentioned may be changed or developed.

    python 如何从内存地址上加载 pythn 对象

    在 python 中我们可以通过 id 函数来获取某个 python 对象的内存地址,或者可以通过调用对象的__repr__魔术函数来获取对象的详细信息

    def tt():
        print(111)
    print(tt.__repr__())
    print(id(tt))
    
    

    但是不知大家是否想过,其实这个内存地址可以直接加载 python 对象的。有两种方法:

    1. PyObj_FromPtr

    在_ctypes 包中,就提供 PyObj_FromPtr 这个 api 去实现我们的需求。代码如下

    def tt():
        print(111)
    print(tt.__repr__())
    print(_ctypes.PyObj_FromPtr(id(tt)))
    

    运行结果如下:

    <function tt at 0x106c628c8>
    <function tt at 0x106c628c8>
    

    2. gc.get_objects

    我们也可以通过 gc 的 get_objects 方法来实现。先来看一下官方介绍

    gc.get_objects()
    Returns a list of all objects tracked by the collector, excluding the list returned.
    

    大致意思为,获取所有可以追踪的对象。所以,我们可以通过第二种方式来实现从特定内存地址加载 python 对象

    def tt():
        print(111)
    print(tt.__repr__())
    
    for i in gc.get_objects():
        if id(i) == id(tt):
            print(i)
            
    

    方法很简单,通过 gc.get_objects 获取所有对象,一一检查这些对象的内存地址是否与给定的内存地址相符,如果相符则返回对象。

    结论

    额,很扯淡的东西,最好不要乱用这种东西。因为出错的话,try except 语句都无法捕捉到这种异常。就当是了解一下吧

    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1049 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 22:53 · PVG 06:53 · LAX 15:53 · JFK 18:53
    ♥ Do have faith in what you're doing.