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)的方式调用

你可能感兴趣的:(c,工作,python,HashMap,File,Class)