魔法函数_字符串表示

版权声明:转载 或者复制请标注来源 https://blog.csdn.net/qq_34979346/article/details/83111776

魔法函数的格式为 :name 双下划线开始和结尾, 魔法函数 不依赖任何类,并且可以随时调用. 增强类的特性和便捷性,读取过源码都知道, 里面都有很多的魔法函数.为了 读取源码,这些必须掌握.

1.str

先看下这个代码段

class Person:
    def __init__(self,person_list):
        self.person_list=person_list

person_list=["andy","xiuwu","maggie"]
person=Person(person_list)
print(person)

想必 大家都知道打印的是什么 , 打印的是 Person 对象:“<main.Person object at 0x0000000002892A20>”.
再看下这个代码段;

class Person:
    def __init__(self,person_list):
        self.person_list=person_list
    def __str__(self):
        return str(self.person_list)

person_list=["andy","xiuwu","maggie"]
person=Person(person_list)

print(person)

打印的结果是 :“[‘andy’, ‘xiuwu’, ‘maggie’]” , 我只是重写了 str 方法, 当我们调用的print,系统会默认掉了 str 方法 print(“persion”)==print(str(persion)), 我重写了以后,当然可以返回一个 list.

猜你喜欢

转载自blog.csdn.net/qq_34979346/article/details/83111776
今日推荐