python的“函数指针”

C++里面有函数指针,想为python也实现一个函数指针,方便函数调用,参考了五年前的一篇博客里的工作:http://blog.csdn.net/dancing999/article/details/1515881

#coding=utf8
"""
# Author: waleking
# Created Time : 六  6/30 14:28:22 2012
  Last Modified: 六  6/30 16:42:23 2012
# File Name: FuncPointer.py
# Description:
实验python的函数指针
来自:http://blog.csdn.net/dancing999/article/details/1515881
提供了类里面的函数指针
在python的类里面,模块名是文件名,模块名可以不等于类名,一个模块下面可以有多个类
"""

class  Test:
	"""
	Class test
	"""
	EventMethods_Test1 = "func1"
	EventMethods_Test2 = 2
	EventMethods_Test3 = 3

	def __init__( self ):
		self.initEventMethods()
		self.EventMethods["func1"]()

	def initEventMethods(self):
		self.EventMethods = {
				Test.EventMethods_Test1: self.EventMethods_Func1,
				Test.EventMethods_Test2: self.EventMethods_Func2,
				Test.EventMethods_Test3: self.EventMethods_Func3,
				}
	def EventMethods_Func1(self):
		print "use the EventMethods_Func1111"

	def EventMethods_Func2(self):
		print "use the EventMethods_Func2222"

	def EventMethods_Func3(self):
		print "use the EventMethods_Func3333"


test=Test()

#===========================================================
#模块中,类外的函数指针调用
def hwFunc1(x):
	print("%s" %(x+1))
	print("waleking's func1")
def hwFunc2(x):
	print("%s" %(x+1))
	print("waleking's func2")


funcSets={"func1":hwFunc1,"func2":hwFunc2}
funcSets["func1"](1)

运行结果是

use the EventMethods_Func1111
2
waleking's func1


总结一下python函数指针的使用方法是:1,写好各个函数;2,写好一个hashmap,key是想要使用的参数,value是函数名;3,用hashmap[key](args)的方式调用

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值