python中魔法方法(持续更新)

1、对于一个自定义的类,如果实现了 __call__ 方法,那么该类的实例对象的行为就是一个函数,是一个可以被调用(callable)的对象。例如:

class Add:
    def __init__(self, n):
         self.n = n
    def __call__(self, x):
        return self.n + x

此时

>>> add = Add(1)
>>> add(4)
5
>>> callable(add)
True

 2、 __call__对象是装有字符串的列表对象,他会覆盖 from import * 的默认行为

下面为文件test1.py

__all__ = ['a', 'b']

c = 5
a = 10
def b():
    return 'b'

下面为test2.py

from test1 import *

print a
print b
print c

运行结果为

10
<function b at 0x0000000002742278>

Traceback (most recent call last):
  File "C:/Users/Administrator/Desktop/test.py", line 5, in <module>
    print c
NameError: name 'c' is not defined
原文地址:https://www.cnblogs.com/milian0711/p/7793074.html