有趣的python 对象描述

在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__






你可能感兴趣的:(有趣的python 对象描述)