2011-02-15 175 views
79

我想知道如何使用python的反射功能將python'type'對象轉換爲字符串。將python'type'對象轉換爲字符串

例如,我想打印對象的類型

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

編輯:順便說一下,謝謝你們,我只是在尋找一個控制檯輸出目的的各類素色印花,沒有什麼花哨。加比的type(someObject).__name__作品就好:)

+1

你認爲一個對象的「類型」是什麼?什麼不適合你發佈的內容? – Falmarri 2011-02-15 20:00:47

+0

道歉,打印類型(someObject)實際上工作:) – 2011-02-15 20:12:34

回答

125
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

+0

做`print(type(someObject))`會打印全名(即包括包) – MageWind 2014-06-30 20:20:22

6
>>> class A(object): pass 

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

你是什麼意思轉換成一個字符串?你可以定義自己的再版海峽 _方法:

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

或我不know..please加解釋相關;)

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