파이썬 버전 2.7.3을 사용하고 있습니다.파이썬의 문자열과 유니 코드 강제/마법 함수는 어떻게 작동합니까?
파이썬에서, 우리는 우리의 사용자 정의 클래스에 str
및 unicode
의 동작을 정의하는 마법의 방법 __str__
및 __unicode__
를 사용
__str__
및
__unicode__
의 반환 값이 강제 변환되는 것을 알 수
>>> class A(object):
def __str__(self):
print 'Casting A to str'
return u'String'
def __unicode__(self):
print 'Casting A to unicode'
return 'Unicode'
>>> a = A()
>>> str(a)
Casting A to str
'String'
>>> unicode(a)
Casting A to unicode
u'Unicode'
중 str
또는 unicode
에 따라 다릅니다.
그러나, 우리가 할 경우이 :
>>> class B(object):
def __str__(self):
print 'Casting B to str'
return A()
def __unicode__(self):
print 'Casting B to unicode'
return A()
>>> b = B()
>>> str(b)
Casting B to str
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
str(b)
TypeError: __str__ returned non-string (type A)
>>> unicode(b)
Casting B to unicode
Traceback (most recent call last):
File "<pyshell#48>", line 1, in <module>
unicode(b)
TypeError: coercing to Unicode: need string or buffer, A found
는 str.mro()
및 unicode.mro()
호출은 모두 basestring
의 서브 클래스 말한다. 그러나 __unicode__
도 개체를 반환 할 수 있으며 이는 object
에서 직접 상속되며 basestring
에서 상속되지 않습니다.
내 질문은 실제로 str
과 unicode
을 호출하면 어떻게됩니까? str
및 unicode
에 사용할 __str__
및 __unicode__
의 반환 값 요구 사항은 무엇입니까?
찾을 수있는 소스 코드를 살펴 봐야 할 수도 있습니다. – Eric