我想知道如何使用python的反射功能将python' type'对象转换为字符串。

例如,我想打印一个对象的类型

print("My type is " + type(some_object))  # (which obviously doesn't work like this)

print(type(some_object).__name__)

如果不适合你,用这个:

print(some_instance.__class__.__name__)

例子:

class A:
    pass
print(type(A()))
# prints <type 'instance'>
print(A().__class__.__name__)
# prints A

此外,在使用新样式类和旧样式类(即从对象继承)时,type()似乎也有不同。对于新样式的类,键入(someObject)。__name__返回名称,对于老式类,它返回实例。


>>> class A(object): pass

>>> e = A()
>>> e
<__main__.A object at 0xb6d464ec>
>>> print type(e)
<class '__main__.A'>
>>> print type(e).__name__
A
>>> 

转换成字符串是什么意思?你可以定义自己的repr和str_方法:

>>> class A(object):
    def __repr__(self):
        return 'hei, i am A or B or whatever'

>>> e = A()
>>> e
hei, i am A or B or whatever
>>> str(e)
hei, i am A or B or whatever

或者我不知道,请解释一下;)


print("My type is %s" % type(someObject)) # the type in python

还是……

print("My type is %s" % type(someObject).__name__) # the object's type (the class you defined)

通过使用str()函数可以做到这一点。

 typeOfOneAsString=str(type(1))  # changes the type to a string type

如果你想使用str()和自定义str方法。这也适用于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'