欢迎光临
我们一直在努力

python3中类的__call__()方法介绍

目录

  • 1 代码
  • 2 解析
    • 2.1 __call__解析
    • 2.2 *atuple和**bdict解析

1 代码

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)

结果为,

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)表示:实例被调用时,不管传多少位置参数、多少关键字参数,都能接住并在函数里用 atuple 和 bdict 处理。

  • 一个 *:表示「接收多余的位置参数」,打包成元组。
  • 两个 **:表示「接收多余的关键字参数」,打包成字典。
赞(0)
未经允许不得转载:171主机测评 » python3中类的__call__()方法介绍
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址