Convert a python 'type' object to a string

前端 未结 5 2022
刺人心
刺人心 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:31

    In case you want to use str() and a custom str method. This also works for repr.

    class TypeProxy:
        def __init__(self, _type):
            self._type = _type
    
        def __call__(self, *args, **kwargs):
            return self._type(*args, **kwargs)
    
        def __str__(self):
            return self._type.__name__
    
        def __repr__(self):
            return "TypeProxy(%s)" % (repr(self._type),)
    
    >>> str(TypeProxy(str))
    'str'
    >>> str(TypeProxy(type("")))
    'str'
    

提交回复
热议问题