2011-02-15 5 views
79

파이썬의 반사 기능을 사용하여 파이썬 'type'객체를 문자열로 변환하는 방법을 알고 싶습니다.python 'type'객체를 문자열로 변환하십시오.

예를 들어, 나는 개체의 유형을 인쇄하고 싶습니다

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

편집 :는, BTW들 덕분에, 방금 콘솔 출력을 위해 유형의 일반 인쇄, 공상 아무것도 찾고 있었다 . 그것이 당신에 맞게하지 않으면 잘 가비의 type(someObject).__name__ 작품 :

+1

당신은 어떤 물체의 "유형"이라고 생각합니까? 그리고 게시 한 내용에 대해 작동하지 않는 것은 무엇입니까? – Falmarri

+0

죄송합니다. 인쇄 유형 (someObject)이 실제로 작동합니다. –

답변

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()와 차이가 new-style 클래스와 old 스타일 (즉, object으로부터의 상속)을 사용할 때. 새 스타일 클래스의 경우 type(someObject).__name__이 이름을 반환하고 구식 클래스의 경우 instance을 반환합니다.

+0

'print (type (someObject)) '를 실행하면 전체 이름 (예 : 패키지 포함) – MageWind

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

또는 내가 explainations를 추가 know..please 해달라고; ...)

+0

Btw가 인쇄됩니다. 나는 당신의 원래 대답이 str (type (someObject))도 도움이되었다고 생각한다. –

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) 
관련 문제