Python中__call__用法实例

yipeiwu_com6年前Python基础

本文实例讲述了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]

如果 这样使用:

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

那么回馈很正常:

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

但如果这样使用:

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__了。

你所举的后面那个例子:

b = Next

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

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

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

相关文章

python/Matplotlib绘制复变函数图像教程

python/Matplotlib绘制复变函数图像教程

今天发现sympy依赖的库mpmath里也有很多数学函数,其中也有在复平面绘制二维图的函数cplot,具体例子如下 from mpmath import * def f1(z):...

Python __getattr__与__setattr__使用方法

比如下面的例子: class Book(object):    def __setattr__(self, name, value):  ...

python的pyecharts绘制各种图表详细(附代码)

python的pyecharts绘制各种图表详细(附代码)

环境:pyecharts库,echarts-countries-pypkg,echarts-china-provinces-pypkg,echarts-china-cities-pypk...

Python多层嵌套list的递归处理方法(推荐)

问题:用Python处理一个多层嵌套list ['and', 'B', ['not', 'A'],[1,2,1,[2,1],[1,1,[2,2,1]]], ['not', 'A',...

python统计cpu利用率的方法

本文实例讲述了python统计cpu利用率的方法。分享给大家供大家参考。具体实现方法如下: #-*-coding=utf-8-*- import win32pdh import ti...