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

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


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

查看所有标签

猜你喜欢:

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

浪潮之巅(下册)

浪潮之巅(下册)

吴军 / 人民邮电出版社 / 2013-6 / 45.00元

《浪潮之巅(第2版)(下册)》不是一本科技产业发展历史集,而是在这个数字时代,一本IT人非读不可,而非IT人也应该阅读的作品。一个企业的发展与崛起,绝非只是空有领导强人即可达成。任何的决策、同期的商业环境,都在都影响着企业的兴衰。《浪潮之巅》不只是一本历史书,除了讲述科技顶尖企业的发展规律,对于华尔街如何左右科技公司,以及金融风暴对科技产业的冲击,也多有着墨。此外,《浪潮之巅》也着力讲述很多尚在普......一起来看看 《浪潮之巅(下册)》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

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

正则表达式在线测试