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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

嵌入式-老费

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值