Home > Backend Development > Python Tutorial > Python中__call__用法实例

Python中__call__用法实例

WBOY
Release: 2016-06-06 11:32:32
Original
1086 people have browsed it

本文实例讲述了Python中__call__的用法,分享给大家供大家参考之用。具体方法如下:

先来看看如下示例代码:

#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]

Copy after login

如果 这样使用:

b = Next(1,7)
print b.List
print b(2)

Copy after login

那么回馈很正常:

[1, 4, 9, 16, 25, 36]
9

Copy after login

但如果这样使用:

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)

Copy after login

__init__是初始化函数,在生成类的实例时执行。

而__call__是模拟()的调用,需要在实例上应用,因此这个实例自然是已经执行过__init__了。

你所举的后面那个例子:

b = Next
Copy after login

这并不是创建实例,而是将class赋给一个变量。因此后面使用b进行的操作都是对Next类的操作,那么其实就是:

Next(1,7)
print Next.List
print Next(2)
Copy after login

希望本文所述对大家的Python程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template