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

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


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

查看所有标签

猜你喜欢:

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

Verilog数字系统设计教程

Verilog数字系统设计教程

夏宇闻 / 北京航空航天大学出版社 / 2003-7-1 / 38.0

《Verilog数字系统设计教程》可作为电子工程类、自动控制类、计算机类的大学本科高年级及研究生教学用书,亦可供其他工程人员自学与参考。一起来看看 《Verilog数字系统设计教程》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试