Convert a python 'type' object to a string

前端 未结 5 2021
刺人心
刺人心 2020-12-02 09:00

I\'m wondering how to convert a python \'type\' object into a string using python\'s reflective capabilities.

For example, I\'d like to print the type of an object

5条回答
  •  甜味超标
    2020-12-02 09:33

    print type(someObject).__name__
    

    If that doesn't suit you, use this:

    print some_instance.__class__.__name__
    

    Example:

    class A:
        pass
    print type(A())
    # prints 
    print A().__class__.__name__
    # prints A
    

    Also, it seems there are differences with type() when using new-style classes vs old-style (that is, inheritance from object). For a new-style class, type(someObject).__name__ returns the name, and for old-style classes it returns instance.

提交回复
热议问题