python(函数指针和类函数指针)

栏目: Python · 发布时间: 7年前

内容简介:python(函数指针和类函数指针)

【 声明:版权所有,欢迎转载,请勿用于商业用途。 联系信箱:feixiaoxing @163.com】

函数指针和类函数指针在 c语言 下面的概念都比较简单,用在脚本下面也很方便。因为脚本语言一切类型都是对象,所以根本不存在指针的概念。一般,我们都是这么用的,

feixiaoxingdeMacBook-Pro-4:~ feixiaoxing$ python
Python 2.7.13 (default, Dec 18 2016, 07:03:34) 
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def process(f):
...     f(1,2,3)
... 
>>> def add(a,b,c):
...     print a,b,c
... 
>>> process(add)
1 2 3
>>>

这种方法用在一般的函数上没有什么问题。但是如果用在了类函数上面,那么就有点麻烦了,

feixiaoxingdeMacBook-Pro-4:~ feixiaoxing$ python
Python 2.7.13 (default, Dec 18 2016, 07:03:34) 
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def process(f):
...     f(1,2,3)
... 
>>> class A:
...     def run(self,a,b,c):
...             print a,b,c
... 
>>> process(A.run)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in process
TypeError: unbound method run() must be called with A instance as first argument (got int instance instead)
>>>

通过系统给出的告警信息,其实 python 已经提示我们要怎么做了,关键是定义一个class实例,用这个实例加上函数作为回调函数就可以了。

feixiaoxingdeMacBook-Pro-4:~ feixiaoxing$ python
Python 2.7.13 (default, Dec 18 2016, 07:03:34) 
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def process(f):
...     f(1,2,3)
... 
>>> class A:
...     def run(self,a,b,c):
...             print a,b,c
... 
>>> val=A()
>>> process(val.run)
1 2 3
>>>

通过代码可以看出,类函数并不复杂。只要将类实例和类函数本身联系在一起,就可以作为普通函数的参数进行使用了。


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Linux设备驱动程序

Linux设备驱动程序

科波特 / 魏永明、耿岳、钟书毅 / 中国电力出版社 / 2006-1-1 / 69.00元

本书是经典著作《Linux设备驱动程序》的第三版。如果您希望在Linux操作系统上支持计算机外部设备,或者在Linux上运行新的硬件,或者只是希望一般性地了解Linux内核的编程,就一定要阅读本书。本书描述了如何针对各种设备编写驱动程序,而在过去,这些内容仅仅以口头形式交流,或者零星出现在神秘的代码注释中。 本书的作者均是Linux社区的领导者。Jonathan Corbet虽不是专职的内核......一起来看看 《Linux设备驱动程序》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具