Getting the class name of an instance?

前端 未结 10 2149
情书的邮戳
情书的邮戳 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:08

    To get instance classname:

    type(instance).__name__
    

    or

    instance.__class__.__name__
    

    both are the same

    0 讨论(0)
  • 2020-11-22 14:12

    In Python 2,

    type(instance).__name__ != instance.__class__.__name__
    # if class A is defined like
    class A():
       ...
    
    type(instance) == instance.__class__
    # if class A is defined like
    class A(object):
      ...
    

    Example:

    >>> class aclass(object):
    ...   pass
    ...
    >>> a = aclass()
    >>> type(a)
    <class '__main__.aclass'>
    >>> a.__class__
    <class '__main__.aclass'>
    >>>
    >>> type(a).__name__
    'aclass'
    >>>
    >>> a.__class__.__name__
    'aclass'
    >>>
    
    
    >>> class bclass():
    ...   pass
    ...
    >>> b = bclass()
    >>>
    >>> type(b)
    <type 'instance'>
    >>> b.__class__
    <class __main__.bclass at 0xb765047c>
    >>> type(b).__name__
    'instance'
    >>>
    >>> b.__class__.__name__
    'bclass'
    >>>
    
    0 讨论(0)
  • 2020-11-22 14:13

    Alternatively you can use the classmethod decorator:

    class A:
        @classmethod
        def get_classname(cls):
            return cls.__name__
    
        def use_classname(self):
            return self.get_classname()
    

    Usage:

    >>> A.get_classname()
    'A'
    >>> a = A()
    >>> a.get_classname()
    'A'
    >>> a.use_classname()
    'A'
    
    0 讨论(0)
  • 2020-11-22 14:14

    You can simply use __qualname__ which stands for qualified name of a function or class

    Example:

    >>> class C:
    ...     class D:
    ...         def meth(self):
    ...             pass
    ...
    >>> C.__qualname__
    'C'
    >>> C.D.__qualname__
    'C.D'
    >>> C.D.meth.__qualname__
    'C.D.meth'
    

    documentation link qualname

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