Python中__call__用法实例
来源:互联网 发布:mysql查看存储引擎 编辑:程序博客网 时间:2024/06/03 19:45
本文实例讲述了Python中__call__的用法,分享给大家供大家参考之用。具体方法如下:
先来看看如下示例代码:
1
2
3
4
5
6
7
8
9
10
#call.py 一个class被载入的情况下。
class
Next
:
List
=
[]
def
__init__(
self
,low,high) :
for
Num
in
range
(low,high) :
self
.
List
.append(Num
*
*
2
)
def
__call__(
self
,Nu):
return
self
.
List
[Nu]
如果 这样使用:
1
2
3
b
=
Next
(
1
,
7
)
print
b.
List
print
b(
2
)
那么回馈很正常:
1
2
[
1
,
4
,
9
,
16
,
25
,
36
]
9
但如果这样使用:
1
2
3
4
5
6
7
8
9
10
11
b
=
Next
b(
1
,
7
)
print
b.
List
print
b(
2
)
$python .
/
call.py
[
1
,
4
,
9
,
16
,
25
,
36
]
Traceback (most recent call last):
File
"cal.py"
, line
17
,
in
<module>
print
b(
2
)
TypeError: __init__() takes exactly
3
arguments (
2
given)
__init__是初始化函数,在生成类的实例时执行。
而__call__是模拟()的调用,需要在实例上应用,因此这个实例自然是已经执行过__init__了。
你所举的后面那个例子:
1
b
=
Next
这并不是创建实例,而是将class赋给一个变量。因此后面使用b进行的操作都是对Next类的操作,那么其实就是:
1
2
3
Next
(
1
,
7
)
print
Next
.
List
print
Next
(
2
)
0 0
- Python中__call__用法实例
- python中 __call__
- python中__init__,__call__学习
- python中__str__, __call__方法
- Python __call__
- python __call__
- Python __call__
- python __call__
- Python __call__
- python中的__call__的个人理解(wsgi实例解释)
- Python可调用对象__call__方法的用法分析
- python中__init__、__getattr__、__setattr__、__call__的使用
- python的__call__
- [Python小菜]__call__是什么
- python __call__ 函数
- Python __new__ ,__init__,__call__
- python的__call__
- Python中的__init__,__call__
- angularjs 基础知识总结
- Spark On YARN内存和CPU分配
- tomcat7.0 内存配置
- JDK并发包---(10)循环栅栏:CyclicBarrier
- 【备忘】关东升-华章培训IOS视频教程【基础编-精通-实战】下载
- Python中__call__用法实例
- angularjs 上传文件
- jersey的简单介绍及与spring-boot的集成使用
- 5-在ORACLE中实现SELECT TOP N
- react native gradle assembleRelease打包运行失败,没有生成bundle文件
- Java就业方向和自学提升方法总结黑马就业班资源分享
- JS - 执行上下文(上)
- 被注入js脚本的xss的解决方法
- 关于帝国cms的优化问题