python列表名是动态的_在Python中查找动态方法的名称

I want to proxy an API over a network. I have the API in a dictionary. I'd like to create a class with the API methods from the dictionary so I can use the API as if I was local. The trouble is finding the name of my dynamically created method. (My approach is based on Adding a Method to an Existing Object and Python dynamic class methods.)

class MainClass(object):

def build_API(self):

methods = dict(meth1='arg1', meth2='arg2')

for key in methods.iterkeys():

setattr(self, key, MethodType(self.default_API, self))

def default_API(self, *args, **kwargs)

called_as_name = ????

self.send_message(called_as_name, args, kwargs)

def send_message(self, called_as_name, *args, **kwargs)

...

# Send API command over network

....

To use this:

api = MainClass()

api.build_API()

api.meth1()

However, everything I try for "called_as_name" always returns "default_API" and never "meth1". How can I get "called_as_name = meth1" when I type "api.meth1()" and "called_as_name = meth2" when I type "api.meth2()"?

I have tried:

curframe = inspect.currentframe()

calframe = inspect.getouterframes(curframe, 2)

called_as_name = calframe[1][3]

called_as_name = inspect.stack()[1][5]

called_as_name = sys._getframe(1).f_code.co_name

解决方案

Trying to do this with actual methods and grabbing the names from the stack frame with that sort of introspection trickery is a recipe for disaster. Instead, make the "methods" be custom callable objects that know their names. Here's a sketch:

class FakeMethod(object):

def __init__(self, name, parent):

self.name = name

self.parent = parent

def __call__(self, *args, **kwargs):

self.parent.send_message(self.name, args, kwargs)

class MainClass(object):

def build_API(self):

methods = dict(meth1='arg1', meth2='arg2')

for key in methods.iterkeys():

setattr(self, key, FakeMethod(key, self))

def send_message(self, called_as_name, *args, **kwargs):

print("Sending message:", called_as_name, args, kwargs)

Then:

>>> api = MainClass()

>>> api.build_API()

>>> api.meth1()

Sending message: meth1 ((), {}) {}

>>> api.meth2()

Sending message: meth2 ((), {}) {}

In theory you could even use __getattr__ on the MainClass to dynamically generate a FakeMethod every time an attribute name is accessed that is not defined but is listed in some list of API method names.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值