美文网首页
随记Python中的魔法方法

随记Python中的魔法方法

作者: 七夜_174e | 来源:发表于2018-08-06 20:57 被阅读0次

在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

相关文章

网友评论

      本文标题:随记Python中的魔法方法

      本文链接:https://www.haomeiwen.com/subject/xffnvftx.html