python3-特殊函数 __call__()

__call__()的本质是将一个类变成一个函数(使这个类的实例可以像函数一样调用)。


【例1】

class Person(object):
    def __init__(self, name, gender):
        self.name = name
        self.gender = gender

    def __call__(self, friend):
        print('My name is %s...' % self.name)
        print('My friend is %s...' % friend)


p = Person("mc", "male")
p("Tim")

输出:

My name is mc...
My friend is Tim...

__call__()模糊了函数和对象之间的概念。

【例2】

class ClassA(object):
    def __new__(cls, *args, **kwargs):
        object = super(ClassA, cls).__new__(cls)
        print("HHHA:0===>")
        return object

    def __init__(self, *args, **kwargs):
        print("HHHB:0===>")

    def __call__(self, func):
        print("HHHC:0===>")
        return func

A = ClassA()

print("HHHH:0====>")

@ClassA()
def hello():
    print("HHHC:0===>hello")

print("HHHH:1====>")

hello()

输出:

HHHA:0===>
HHHB:0===>
HHHH:0====>  //__call__()未调用
HHHA:0===>
HHHB:0===>
HHHC:0===>  //__call__()被调用
HHHH:1====>
HHHC:0===>hello

类生成实例时不会调用__call__(),但在作为装饰器时__call__()被调用。

猜你喜欢

转载自blog.csdn.net/menghaocheng/article/details/83317045