python '魔法‘’函数 __call__, __repr__, __str__

    python中许多的内建‘魔法’函数:最近学习到这三个:__call__, __repr__, _str__,就放到一起做个笔记。

    废话不多说,直接撸上最简单的代码:

class A:
    def __repr__(self):
        return '<this is __repr__>'
    def __call__(self):
        print('<this is __call__>')
    def __str__(self):
        return '<this is __str__>'

实例化进行调用,结果如下:

>>> a = A()
>>> a
<this is __repr__>
>>> print(a)
<this is __str__>
>>> a()
<this is __call__>

结果分析:

    i. 实例化后,直接调用实例(不加点运算符),内部调用的是 __repr__ 函数

   ii. 通过 print 函数调用实例(不加点运算符),内部调用的是 __str__ 函数

  iii. 实例直接加上括号(如果有参数,传参),内部调用的是 __call__ 函数(实现:可以直接通过实例调用,不用加点运算符)

ps:对于 __repr__ 和 __str__ 还有如下的区别:

    __repr__ 函数:如果没有显式的定义此函数,进行调用,会返回一个代理(即对象在内存的位置)

    __str__ 函数:通常与 __rerp__ 返回的结果相同,但有时候返回的结果更有说明性

>>> from datetime import date
>>> today = date(2011, 9, 12)
>>> repr(today)
'datetime.date(2011, 9, 12)'
>>> str(today)
'2011-09-12'

猜你喜欢

转载自blog.csdn.net/yzmumu/article/details/82817982