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

2017-08-23 17:01:10 +08:00
 modm
例如

from foo import a
b = object()

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

请不要问我为什么有这种需求= =
2323 次点击
所在节点    Python
7 条回复
ekeyme
2017-08-23 17:14:14 +08:00
print(b.__module__)
print(a.__module__)
twistoy
2017-08-23 17:19:31 +08:00
如果是
from foo import bar
a = bar()

那这个 a 算是引入的还是不引入的
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
2017-08-24 10:29:42 +08:00
虽然你不让问
但我还是想问
为什么有这种需求?
modm
2017-08-24 10:43:30 +08:00
@jmc891205 想扫描一个 package 下面某个 Class 的所有 instance,并记录其文件路径, 如果有引用的情况,扫描的时候这个 instance 会有重复,无法知道真正的路径是哪。
modm
2017-08-24 10:45:39 +08:00
@ekeyme 如果 a 是继承,貌似 module 的路径是父类的路径
modm
2017-08-24 10:56:57 +08:00
打算用 inspect.getsource(module) ,先通过代码正则判断是不是引用的了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/385225

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX