Getting the class name of an instance?

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

    Have you tried the __name__ attribute of the class? ie type(x).__name__ will give you the name of the class, which I think is what you want.

    >>> import itertools
    >>> x = itertools.count(0)
    >>> type(x).__name__
    'count'
    

    If you're still using Python 2, note that the above method works with new-style classes only (in Python 3+ all classes are "new-style" classes). Your code might use some old-style classes. The following works for both:

    x.__class__.__name__
    

提交回复
热议问题