推荐学习书目
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
modm
V2EX  ›  Python

Python 中如何判断一个 object 是从其他 module 引入的呢

  •  
  •   modm · Aug 23, 2017 · 3327 views
    This topic created in 3198 days ago, the information mentioned may be changed or developed.
    例如

    from foo import a
    b = object()

    怎么知道 a 是引入的,b 不是

    请不要问我为什么有这种需求= =
    Supplement 1  ·  Aug 24, 2017
    a 是 object 不是 class
    7 replies    2017-08-24 10:56:57 +08:00
    ekeyme
        1
    ekeyme  
       Aug 23, 2017
    print(b.__module__)
    print(a.__module__)
    twistoy
        2
    twistoy  
       Aug 23, 2017
    如果是
    from foo import bar
    a = bar()

    那这个 a 算是引入的还是不引入的
    hl
        3
    hl  
       Aug 23, 2017
    https://docs.python.org/2/library/inspect.html#types-and-members

    __module__ name of module in which this class was defined


    In [1]: class a:
    ...: pass
    ...:

    In [2]: b = a()

    In [3]: from hashlib import md5

    In [4]: c = md5()

    In [24]: inspect.getmodule(a)
    Out[24]: <module '__main__'>

    In [25]: inspect.getmodule(b)
    Out[25]: <module '__main__'>

    In [27]: inspect.getmodule(c)

    In [28]: inspect.getmodule(md5)
    Out[28]: <module '_hashlib' from '/Users/liuqian/anaconda/lib/python3.6/lib-dynload/_hashlib.cpython-36m-darwin.so'>
    jmc891205
        4
    jmc891205  
       Aug 24, 2017
    虽然你不让问
    但我还是想问
    为什么有这种需求?
    modm
        5
    modm  
    OP
       Aug 24, 2017
    @jmc891205 想扫描一个 package 下面某个 Class 的所有 instance,并记录其文件路径, 如果有引用的情况,扫描的时候这个 instance 会有重复,无法知道真正的路径是哪。
    modm
        6
    modm  
    OP
       Aug 24, 2017
    @ekeyme 如果 a 是继承,貌似 module 的路径是父类的路径
    modm
        7
    modm  
    OP
       Aug 24, 2017
    打算用 inspect.getsource(module) ,先通过代码正则判断是不是引用的了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3282 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 11:46 · PVG 19:46 · LAX 04:46 · JFK 07:46
    ♥ Do have faith in what you're doing.