__call__函数

一、定义

在Python中,__call__函数是一个特殊的方法,用于使一个对象可以像函数一样被调用。当一个对象定义了__call__方法时,它就成为了一个可调用对象。

二、使用

class Counter:
    def __init__(self):
        self.count = 0

    def __call__(self):
        self.count += 1
        print(f"Count is {self.count}")

c = Counter()
c()  # 调用 __call__ 方法,输出 "Count is 1"
c()  # 调用 __call__ 方法,输出 "Count is 2"

__call__函数_第1张图片

你可能感兴趣的:(python,python,开发语言)