将python'type'对象转换为字符串

时间:2011-02-15 19:58:05

标签: python reflection

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

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

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

编辑:顺便说一句,谢谢大家,我只是在寻找用于控制台输出目的的普通打印类型,没什么特别的。 Gabi的type(someObject).__name__效果很好:)

5 个答案:

答案 0 :(得分:176)

print type(someObject).__name__

如果这不适合你,请使用:

print some_instance.__class__.__name__

示例:

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

此外,当使用新式类与旧式(即type()的继承)时,似乎与object存在差异。对于新式类,type(someObject).__name__返回名称,对于旧式类,它返回instance

答案 1 :(得分:7)

>>> 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

或者我不知道..请加上解释;)

答案 2 :(得分:4)

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)

答案 3 :(得分:1)

使用str()

 typeOfOneAsString=str(type(1))

答案 4 :(得分:0)

如果您想使用str()和自定义的 str 方法。这也适用于代表。

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'