Python - 面向对象编程 - __str__()

时间:2021-08-29 20:28:00   收藏:0   阅读:12

为什么要讲 __str__

 

重点

必须返回字符串

 

不使用 __str__ 的栗子

class PoloBlog:
    def __init__(self, name):
        self.name = name


blog1 = PoloBlog("小菠萝")
print(blog1)


# 输出结果
<__main__.PoloBlog object at 0x1078a4dc0>

 

新增 __str__ 方法

class PoloBlog:
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return "name is %s" % self.name


blog1 = PoloBlog("小菠萝")
print(blog1)


# 输出结果
name is 小菠萝

 

原文:https://www.cnblogs.com/poloyy/p/15202541.html

评论(0)
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!