# -*- coding: utf-8 -*- import inspect #装饰器,设置_rpc_public_name属性,方便inspect.getmembers进行筛选 def public(name=None): if callable(name): f = name f._rpc_public_name = f.__name__ return f def _(f): f._rpc_public_name = name or f.__name__ return f return _ class abc(): def __init__(self): self.a=1 self.b=2 self.method_map={} @public("funas") def funas(self): print("funas123456789") @public("hello") def hello(self): print("hello") #登记函数方法 def register_public_methods(self): for name, f in inspect.getmembers( self, lambda f: callable(f) and hasattr(f, '_rpc_public_name') ): print(f) self.add_method(f, f._rpc_public_name) def add_method(self,fun, name): self.method_map[name]=fun if __name__=="__main__": a=abc() a.register_public_methods() #从self.method.map中获取已经登记的方法 method=a.method_map["funas"] #调用方法 method() method = a.method_map["hello"] method() print a.method_map
执行结果:前两句输出为调用register_public_methods函数调用时的输出,
3,4行是调用方法的输出,最后两行时把存储方法的字典打印
<bound method abc.funas of <__main__.abc instance at 0x109aebd40>>
<bound method abc.hello of <__main__.abc instance at 0x109aebd40>>
funas123456789
hello
{'hello': <bound method abc.hello of <__main__.abc instance at 0x109aebd40>>,
'funas': <bound method abc.funas of <__main__.abc instance at 0x109aebd40>>}