Getting the class name of an instance?

前端 未结 10 2174
情书的邮戳
情书的邮戳 2020-11-22 13:38

How do I find out a name of class that created an instance of an object in Python if the function I am doing this from is the base class of which the class of the instance h

10条回答
  •  遇见更好的自我
    2020-11-22 14:02

    Apart from grabbing the special __name__ attribute, you might find yourself in need of the qualified name for a given class/function. This is done by grabbing the types __qualname__.

    In most cases, these will be exactly the same, but, when dealing with nested classes/methods these differ in the output you get. For example:

    class Spam:
        def meth(self):
            pass
        class Bar:
            pass
    
    >>> s = Spam()
    >>> type(s).__name__ 
    'Spam'
    >>> type(s).__qualname__
    'Spam'
    >>> type(s).Bar.__name__       # type not needed here
    'Bar'
    >>> type(s).Bar.__qualname__   # type not needed here 
    'Spam.Bar'
    >>> type(s).meth.__name__
    'meth'
    >>> type(s).meth.__qualname__
    'Spam.meth'
    

    Since introspection is what you're after, this is always you might want to consider.

提交回复
热议问题