轉自:http://blog.csdn.net/woshiaotian/article/details/20705801
在python 中可以自定義類, 類實例的描述信息可以有三個函數定義,對比java,我們會發現java只有一個toString()函數,這是因爲
在java虛擬機中所有的字符串都是unicode或者說utf-16。python 則提供更多了函數。
那麼在各種情況下,誰先被調用呢?
參考
http://docs.python.org/2/reference/datamodel.html#object.__unicode__
- # -*- coding:utf-8 -*-
- class Person(object):
- def __init__(self):
- self.name = u"張三"
- self.age = 15
- def __repr__(self):
- return '__repr__'
- def __str__(self):
- return '__str__'
- def __unicode__(self):
- return '__unicode__'
- p = Person()
- print p
- print u"你好,%s" % (p)
- x = u"你好,%s" % (p)
- print type(x)
執行結果:
aotian@aotian-home:/tmp$ python report.py
__str__
你好,__unicode__
<type 'unicode'>
從結果可以看出, python 解釋器可以根據場景自動判斷該使用哪個函數,根據實驗表明:
場景1--需要unicode
調用順序(如果一個不存在,則調用另一個)
__unicode__ -> __str__ -> __repr__
場景2--需要str
調用順序
__str__ -> __repr__