Python中如何判断一个object是从其他module引入的
例如
from foo import a
b = object()
怎么知道 a 是引入的,b 不是
请不要问我为什么有这种需求= =
Python中如何判断一个object是从其他module引入的
print(b.module)
print(a.module)
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©
In [28]: inspect.getmodule(md5)
Out[28]: <module ‘_hashlib’ from ‘/Users/liuqian/anaconda/lib/python3.6/lib-dynload/_hashlib.cpython-36m-darwin.so’>
虽然你不让问
但我还是想问
为什么有这种需求?
想扫描一个 package 下面某个 Class 的所有 instance,并记录其文件路径, 如果有引用的情况,扫描的时候这个 instance 会有重复,无法知道真正的路径是哪。
如果 a 是继承,貌似 module 的路径是父类的路径
打算用 inspect.getsource(module) ,先通过代码正则判断是不是引用的了


