V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2017-08-23 17:01:10 +08:00 · 2306 次点击
    这是一个创建于 2431 天前的主题,其中的信息可能已经有所发展或是发生改变。
    例如

    from foo import a
    b = object()

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

    请不要问我为什么有这种需求= =
    第 1 条附言  ·  2017-08-24 10:45:05 +08:00
    a 是 object 不是 class
    7 条回复    2017-08-24 10:56:57 +08:00
    ekeyme
        1
    ekeyme  
       2017-08-23 17:14:14 +08:00
    print(b.__module__)
    print(a.__module__)
    twistoy
        2
    twistoy  
       2017-08-23 17:19:31 +08:00
    如果是
    from foo import bar
    a = bar()

    那这个 a 算是引入的还是不引入的
    hl
        3
    hl  
       2017-08-23 18:03:08 +08:00
    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  
       2017-08-24 10:29:42 +08:00
    虽然你不让问
    但我还是想问
    为什么有这种需求?
    modm
        5
    modm  
    OP
       2017-08-24 10:43:30 +08:00
    @jmc891205 想扫描一个 package 下面某个 Class 的所有 instance,并记录其文件路径, 如果有引用的情况,扫描的时候这个 instance 会有重复,无法知道真正的路径是哪。
    modm
        6
    modm  
    OP
       2017-08-24 10:45:39 +08:00
    @ekeyme 如果 a 是继承,貌似 module 的路径是父类的路径
    modm
        7
    modm  
    OP
       2017-08-24 10:56:57 +08:00
    打算用 inspect.getsource(module) ,先通过代码正则判断是不是引用的了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5348 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 43ms · UTC 09:05 · PVG 17:05 · LAX 02:05 · JFK 05:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.