zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

Python 函数指针
2023-09-27 14:27:11 时间

【 声明:版权所有,欢迎转载,请勿用于商业用途。 联系信箱: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
>>> 

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