반응형
python 'type' 개체를 문자열로 변환합니다.
python의 반사 기능을 사용하여 python 'type' 객체를 문자열로 변환하는 방법을 알고 싶습니다.
예를 들어, 개체의 유형을 인쇄하고 싶습니다.
print("My type is " + type(some_object)) # (which obviously doesn't work like this)
print(type(some_object).__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()
및 커스텀 스트링 메서드.이것은 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'
str() 함수를 사용하면 이를 수행할 수 있습니다.
typeOfOneAsString=str(type(1)) # changes the type to a string type
언급URL : https://stackoverflow.com/questions/5008828/convert-a-python-type-object-to-a-string
반응형
'programing' 카테고리의 다른 글
연관지을 수 있는 어레이에서 키와 그 값을 삭제하려면 어떻게 해야 합니까? (0) | 2022.09.15 |
---|---|
Javascript V8 속도를 얻기 위해 Ruby, Python을 차단하는 것은 무엇입니까? (0) | 2022.09.15 |
panda DataFrame에서 특정 열 이름 변경 (0) | 2022.09.15 |
Python에서 현재 사용자 이름을 얻을 수 있는 휴대용 방법이 있나요? (0) | 2022.09.15 |
JavaScript 개체의 첫 번째 키 이름을 가져옵니다. (0) | 2022.09.15 |