将python“type”对象转换为string
我想知道如何使用python的reflectionfunction将python“type”对象转换为string。
例如,我想打印一个对象的types
print "My type is " + type(someObject) # (which obviously doesn't work like this)   编辑:顺便说一句,谢谢你,我只是寻找简单的打印types的控制台输出的目的,没有什么幻想。  Gabi的type(someObject).__name__工作正常:) 
 print type(someObject).__name__ 
如果这不适合你,使用这个:
 print some_instance.__class__.__name__ 
例:
 class A: pass print type(A()) # prints <type 'instance'> print A().__class__.__name__ # prints A 
 而且,在使用新样式类和旧样式(即从objectinheritancetype()时,似乎与type()有所不同。 对于新样式类, type(someObject).__name__返回名称,对于旧式类,则返回instance 。 
 >>> class A(object): pass >>> e = A() >>> e <__main__.A object at 0xb6d464ec> >>> print type(e) <class '__main__.A'> >>> print type(e).__name__ A >>> 
转换成string是什么意思? 你可以定义你自己的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)