Python3中__call__方法介绍
2022/1/5 20:04:05
本文主要是介绍Python3中__call__方法介绍,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
如果Python3类中有__call__方法,那么此类实例的行为类似于函数并且可以像函数一样被调用。当实例作为函数被调用时,如果定义了此方法,则x(arg1, arg2, …)是x.__call__(arg1, arg2, …)的简写。
为了将一个类实例当作函数调用,我们需要在类中实现__call__()方法。该方法的功能类似于在类中重载()运算符,使得类实例对象可以像调用普通函数那样,以”对象名()”的形式使用。
以下为测试代码:
var = 2 if var == 1: # https://www.geeksforgeeks.org/__call__-in-python/ class Example: def __init__(self): print("Instance Created") # Defining __call__ method def __call__(self): print("Instance is called via special method") e = Example() # Instance created # __init__ method will be called e() # Instance is called via special method # __call__ method will be called elif var == 2: class Product: def __init__(self): print("Instance Created") # Defining __call__ method def __call__(self, a, b): # 可以定义任意参数 print(a * b) ans = Product() # Instance created # __init__ method will be called ans(10, 20) # 200 # __call__ method will be called ans.__call__(10, 20) # 等价于ans(10, 20) print("test finish")
GitHub:https://github.com/fengbingchun/Python_Test
这篇关于Python3中__call__方法介绍的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python