Python __call__()方法(详解版)

1年前 (2024-04-27)
本节再介绍 Python 类中一个非常特殊的实例方法,即 __call__()。该方法的功能类似于在类中重载 () 运算符,使得类实例对象可以像调用普通函数那样,以“对象名()”的形式使用。

举个例子:

class CLanguage:

# 定义__call__方法

def __call__(self,name,add):

print("调用__call__()方法",name,add)

clangs = CLanguage()

clangs("C语言中文网","http://c.biancheng网站站点" rel="nofollow" />

调用__call__()方法 C语言中文网 http://c.biancheng网站站点" rel="nofollow" /> 可调用对象。可调用对象包括自定义的函数、Python 内置函数以及本节所讲的类实例对象。

对于可调用对象,实际上“名称()”可以理解为是“名称.__call__()”的简写。仍以上面程序中定义的 clangs 实例对象为例,其一行代码还可以改写为如下形式:

clangs.__call__("C语言中文网","http://c.biancheng网站站点" rel="nofollow" />

def say():

print("Python教程:http://c.biancheng网站站点" rel="nofollow" /> Python教程:http://c.biancheng网站站点" rel="nofollow" />

class CLanguage:

def __init__ (self):

self.name = "C语言中文网"

self.add = "http://c.biancheng网站站点" rel="nofollow" /> False
**********

True

可以看到,由于 name 是类属性,它没有以 __call__ 为名的 __call__() 方法;而 say 是类方法,它是可调用对象,因此它有 __call__() 方法。