python中__call__方法示例分析

yipeiwu_com6年前Python基础

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

Python中的__call__允许程序员创建可调用的对象(实例),默认情况下, __call__()方法是没有实现的,这意味着大多数实例是不可调用的。然而,如果在类定义中覆盖了这个方法,那么这个类的实例就成为可调用的。

test.py文件如下:

#!/usr/bin/python
# Filename:test.py
 
class CallTest():
  def __init__(self):
    print 'init'
 
  def __call__(self):
    print 'call'
 
call_test = CallTest()

执行结果:
没有重写__call__:

>>> from test import CallTest
init
>>> t = CallTest()
init
>>> callable(t)
False
>>> t()
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
AttributeError: CallTest instance has no __call__ method
>>>

重写__call__:

>>> from test import CallTest
init
>>> t = CallTest()
init
>>> callable(t)
True
>>> t()
call
>>>

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

相关文章

详解PyTorch手写数字识别(MNIST数据集)

详解PyTorch手写数字识别(MNIST数据集)

MNIST 手写数字识别是一个比较简单的入门项目,相当于深度学习中的 Hello World,可以让我们快速了解构建神经网络的大致过程。虽然网上的案例比较多,但还是要自己实现一遍。代码采...

django基于restframework的CBV封装详解

一.models数据库映射 from django.db import models # Create your models here. class Book(models.Mo...

在python里从协程返回一个值的示例

下面的例子演法了怎么样从协程里返回一个值: import asyncio async def coroutine(): print('in coroutine') ret...

python实现在字符串中查找子字符串的方法

本文实例讲述了python实现在字符串中查找子字符串的方法。分享给大家供大家参考。具体如下: 这里实现python在字符串中查找子字符串,如果找到则返回子字符串的位置,如果没有找到则返回...

python requests指定出口ip的例子

爬虫需要,一个机器多个口,一个口多个ip,为轮询这些ip demo #coding=utf-8 import requests,sys,socket from requests_to...