将 python 'type' 对象转换为字符串 [英] Convert a python 'type' object to a string
本文介绍了将 python 'type' 对象转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何使用 python 的反射功能将 python 'type' 对象转换为字符串.
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
print "My type is " + type(someObject) # (which obviously doesn't work like this)
推荐答案
print type(someObject).__name__
如果这不适合您,请使用此:
If that doesn't suit you, use this:
print some_instance.__class__.__name__
示例:
class A:
pass
print type(A())
# prints <type 'instance'>
print A().__class__.__name__
# prints A
此外,在使用新式类与旧式(即从 object
继承)时,type()
似乎存在差异.对于新式类,type(someObject).__name__
返回名称,而对于旧式类,它返回 instance
.
Also, it seems there are differences with type()
when using new-style classes vs old-style (that is, inheritance from object
). For a new-style class, type(someObject).__name__
returns the name, and for old-style classes it returns instance
.
这篇关于将 python 'type' 对象转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文