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


152

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

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

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

1
您认为对象的“类型”是什么?而且您发布的内容无效吗?
法尔玛里

抱歉,打印type(someObject)确实有效:)
Rehno Lindeque 2011年

Answers:


223
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


3
Doing print(type(someObject))将打印全名(即包括包裹)
MageWind 2014年

7
>>> class A(object): pass

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

转换为字符串是什么意思?您可以定义自己的reprstr _方法:

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

还是我不知道..请添加说明;)


顺便说一句。我认为您的原始答案具有str(type(someObject)),这也很有帮助
Rehno Lindeque 2011年

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)


1

如果您想使用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'
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.