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

后端 未结 1 1463
情话喂你
情话喂你 2021-01-18 06:46

I want to obtain the module from which a Python object is from. Both

x.__module__

and

x.__class__.__module__
相关标签:
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.

    0 讨论(0)
提交回复
热议问题