在Python中查找动态方法的名称 [英] Find name of dynamic method in Python

查看:287
本文介绍了在Python中查找动态方法的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过网络代理API.我在字典中有API.我想用字典中的API方法创建一个类,以便可以像使用本地API一样使用该API.麻烦在于找到我动态创建的方法的名称. (我的方法基于添加现有对象的方法和 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
        ....

要使用此功能:

api = MainClass()
api.build_API()
api.meth1()

但是,我尝试的所有名为"as_name"都始终返回"default_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()"?

我尝试过:

curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 2)
called_as_name = calframe[1][3]

来自 Python:如何在被调用方法中获取调用者的方法名称?

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

在Python的另一个函数中获取调用者函数名称?

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

来自在Python的另一个函数中获取调用者函数名称吗?

推荐答案

尝试使用实际方法执行此操作,并使用这种自省技巧从堆栈框架中获取名称,这是灾难的根源.而是使方法"成为知道其名称的自定义可调用对象.这是草图:

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)

然后:

>>> api = MainClass()
>>> api.build_API()
>>> api.meth1()
Sending message: meth1 ((), {}) {}
>>> api.meth2()
Sending message: meth2 ((), {}) {}

理论上,每次访问未定义但在API方法名称列表中列出的属性名称,您甚至可以在MainClass上使用__getattr__动态生成FakeMethod.

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.

这篇关于在Python中查找动态方法的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆