반응형
파이썬 'type'객체를 문자열로 변환
파이썬의 반사 기능을 사용하여 파이썬 '유형'객체를 문자열로 변환하는 방법이 궁금합니다.
예를 들어, 객체의 유형을 인쇄하고 싶습니다
print "My type is " + type(someObject) # (which obviously doesn't work like this)
편집 : Btw, 고마워, 콘솔 출력 목적으로 일반 유형의 인쇄를 찾고 있었지만 멋진 것은 아닙니다. 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
또한 type()
새로운 스타일의 클래스와 올드 스타일 (의 상속 object
) 을 사용할 때 와 다른 점이 있습니다 . 새 스타일 클래스의 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
>>>
문자열로 변환한다는 것은 무엇을 의미합니까? 자신 만의 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)
str () 사용
typeOfOneAsString=str(type(1))
사용하려는 경우 str()
및 사용자 정의 str 메소드. 이것은 repr에도 적용됩니다.
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'
참고 URL : https://stackoverflow.com/questions/5008828/convert-a-python-type-object-to-a-string
반응형
'IT박스' 카테고리의 다른 글
파일 또는 어셈블리 'System.Data.SQLite'를로드 할 수 없습니다 (0) | 2020.07.12 |
---|---|
#define, enum 또는 const를 사용해야합니까? (0) | 2020.07.11 |
Objective-C 대신 Cocoa와 함께 C ++를 사용 하시겠습니까? (0) | 2020.07.11 |
SQL Server SELECT LAST N 행 (0) | 2020.07.11 |
StartCoroutine / yield return pattern은 Unity에서 실제로 어떻게 작동합니까? (0) | 2020.07.11 |