Obtaining module name: x.__module__ vs x.__class__.__module__

本秂侑毒 提交于 2019-12-19 19:52:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!