1. 程式人生 > >python3-特殊函式 __call__()

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__()被呼叫。