栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python 的

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python 的

python 有一组内置(built-in)方法,__call__就是其中一种。__call__方法使python类的实例化对象可以像函数一样被调用。

具体而言,当一个类定义了__call__方法,则它的实例化对象作为函数调用时:x(arg1, arg2, ...)等价于x.__call__(arg1, arg2, ...).

例子一

class Example:
    def __init__(self):
        print("Instance Created")
      
    # 定义__call__方法
    def __call__(self):
        print("Instance is called via special method")
# 实例化一个 Example 类的对象 e
e = Example()
# 输出:Instance Created
# __call__方法将被对象 e 调用
e()
# 输出:Instance is called via special method

例子二

class Product:
    def __init__(self):
        print("Instance Created")
  
    # Defining __call__ method
    def __call__(self, a, b):
        print(a * b)
# Instance created
ans = Product()
# output: Instance Created
# __call__ method will be called
ans(10, 20)
# output: 200
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/925879.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号