问题
I want to obtain the module from which a Python object is from. Both
x.__module__
and
x.__class__.__module__
seem to work. Are these completely redundant? Is there any reason to prefer one over another?
回答1:
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'
For an instance which doesn't define __module__
directly the attribute from the class is used instead.
>>> Example().__module__
'__main__'
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.
来源:https://stackoverflow.com/questions/5271112/obtaining-module-name-x-module-vs-x-class-module