在python中方法名如果是_xxxx_()的,那么就有特殊的功能,因此叫做“魔法”方法,
当使用print输出对象的时候,只要自己定义了_str_(self)方法,那么就会打印从在这个方法中return的数据
class Test(object):
def __init__(self, world):
self.world = world
def __str__(self):
return 'world is %s str' % self.world
def __repr__(self):
return 'world is %s repr' % self.world
t = Test('world_big')
print (t)
print (t.__repr__())
world is world_big str
world is world_big repr
其实_str_ 相当于是str()方法 而_repr_ 相当于repr()方法。str是针对于让人更好理解的字符串格式化,而repr是让机器更好理解的字符串格式化。
更多的魔法方法看csdn








网友评论