获取模块名称:x .__ module__与x .__ class __.__ module__ [英] Obtaining module name: x.__module__ vs x.__class__.__module__
问题描述
我想获取Python对象所来自的模块.两者
I want to obtain the module from which a Python object is from. Both
x.__module__
和
x.__class__.__module__
似乎可以正常工作.这些完全多余吗?有什么理由比另一个更喜欢吗?
seem to work. Are these completely redundant? Is there any reason to prefer one over another?
推荐答案
如果x
是一个类,则x.__module__
和x.__class__.__module__
会给您带来不同的东西:
If x
is a class then x.__module__
and x.__class__.__module__
will give you different things:
# (Python 3 sample; use 'class Example(object): pass' for Python 2)
>>> class Example: pass
>>> Example.__module__
'__main__'
>>> Example.__class__.__module__
'builtins'
对于未直接定义__module__
的实例,将使用类中的属性代替.
For an instance which doesn't define __module__
directly the attribute from the class is used instead.
>>> Example().__module__
'__main__'
我认为您需要弄清楚您真正想知道的模块.如果它是包含类定义的模块,那么最好对此进行明确说明,因此我将使用x.__class__.__module__
.实例通常不会在其创建位置记录模块,因此x.__module__
可能会引起误解.
I think you need to be clear what module you actually want to know about. If it is the module containing the class definition then it is best to be explicit about that, so I would use x.__class__.__module__
. Instances don't generally record the module where they were created so x.__module__
may be misleading.
这篇关于获取模块名称:x .__ module__与x .__ class __.__ module__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!