常用内置方法之:__str__,__repr__

class Test(object):
	def __init__(self):
		pass

	def __str__(self):
		return "test"


test = Test()
print test

>>>test

  如上所示,print 方法默认调用的是对象的__str__方法

class Test(object):
	def __init__(self):
		pass

	def __repr__(self):
		return "test"


test = Test()
print test

>>>test

  如上所示,如果当前位置找不到__str__,使用print语句时候,会调用__repr__方法,反之,如果不存在__repr__,就算当前位置有__str__也不会调用\

class Test(object):
	def __init__(self):
		pass


test = Test()
print test

>>><__main__.Test object at 0x0000000003A9F6D8>

  默认情况下,__str__返回的当前对象的地址:字符串形式要注意的是,__str__必须return 一个字符串,否则会报错

猜你喜欢

转载自www.cnblogs.com/chenadong/p/9557799.html