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

Reh*_*que 127 python reflection

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

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

print "My type is " + type(someObject) # (which obviously doesn't work like this)
Run Code Online (Sandbox Code Playgroud)

编辑:顺便说一句,谢谢大家,我只是寻找简单的打印类型的控制台输出目的,没有什么花哨的.加比的type(someObject).__name__作品很好:)

Gab*_*aru 197

print type(someObject).__name__
Run Code Online (Sandbox Code Playgroud)

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

print some_instance.__class__.__name__
Run Code Online (Sandbox Code Playgroud)

例:

class A:
    pass
print type(A())
# prints <type 'instance'>
print A().__class__.__name__
# prints A
Run Code Online (Sandbox Code Playgroud)

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

  • 执行`print(type(someObject))`将打印全名(即包括包) (3认同)

Ant*_*Ant 7

>>> class A(object): pass

>>> e = A()
>>> e
<__main__.A object at 0xb6d464ec>
>>> print type(e)
<class '__main__.A'>
>>> print type(e).__name__
A
>>> 
Run Code Online (Sandbox Code Playgroud)

你是什​​么意思转换成字符串?你可以定义自己的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
Run Code Online (Sandbox Code Playgroud)

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


小智 6

print("My type is %s" % type(someObject)) # the type in python
Run Code Online (Sandbox Code Playgroud)

或者...

print("My type is %s" % type(someObject).__name__) # the object's type (the class you defined)
Run Code Online (Sandbox Code Playgroud)


kil*_*joy 5

如果您想使用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'
Run Code Online (Sandbox Code Playgroud)