python3中类的__call__()方法介绍

目录

  • [1 代码](#1 代码)
  • [2 解析](#2 解析)
    • [2.1 __call__解析](#2.1 __call__解析)
    • [2.2 *atuple和**bdict解析](#2.2 *atuple和**bdict解析)

1 代码

py 复制代码
import os
import time
import sys

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __call__(self, *atuple, **bdict):
        print(f"len(atuple) = {len(atuple)}!")
        for x in atuple:
            print(f"x = {x}!")
        print(f"len(bdict) = {len(bdict)}!")
        for k, v in bdict.items():
            print(f"k = {k}, v = {v}!")
        return

if __name__ == "__main__":
    print("start")
    print("end")
    stu = Student("John", 20)
    stu(1, 2, 3, apple=4, banana=5, cherry=6, orange=7)

结果为,

txt 复制代码
start
end
len(atuple) = 3!
x = 1!
x = 2!
x = 3!
len(bdict) = 4!
k = apple, v = 4!
k = banana, v = 4!
k = cherry, v = 5!
k = orange, v = 6!

2 解析

2.1 __call__解析

方法 前面是什么 发生的事
ClassName() 类(class) 实例化:创建新对象,执行 init (以及 new
instance() 实例(object) 调用:把实例当函数用,执行 instance.call(...)

类( ... ) → 实例化(造对象)。

对象( ... ) → 调用(执行该对象的 __call__)。

2.2 *atuple和**bdict解析

写法 含义 函数内类型
*atuple 多余位置参数 tuple
**bdict 多余关键字参数 dict

这样写__call__(self, *atuple, **bdict)表示:实例被调用时,不管传多少位置参数、多少关键字参数,都能接住并在函数里用 atuplebdict 处理。

  • 一个 *:表示「接收多余的位置参数」,打包成元组。
  • 两个 **:表示「接收多余的关键字参数」,打包成字典。
相关推荐
默_笙1 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
小羊没烦恼!1 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
qq_426003961 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫1 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技1 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读1 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时1 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
C语言小火车1 天前
C/C++ 为什么需要编译器?
开发语言·c++
奇思妙想聪明勤奋的小羊1 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1231 天前
2026年第38周GitHub趋势周报
python·科技·github