python - 如何动态代理类的方法?

标签 python python-2.7

我想使用以下代码代理一个类的“所有”方法:

import paramiko

class SFTPProxy():
    def __init__(self, sftp):
        self.sftp = TRANSPORT.open_sftp_client()
        for x, y in type(self.sftp).__dict__.items():
            if re.search(r'^__', x):
                continue
            def fn(self, *args, **kwargs):
                return y(self.sftp, *args, **kwargs)
            setattr(SFTPProxy, x, fn)

当我这样调用方法时:

fooproxy.sftp.listdir()

有效。

当我这样调用方法时:

fooproxy.listdir()  # this is the method belongs to the proxied class

程序直接挂了,是不是代码有什么浅层问题?

最佳答案

我在您的方法中看到的一个问题是,并非 type(self.sftp).__dict__ 中的所有值都是函数。因此,y(...) 将失败。覆盖 __getattr__ 不是更简单、更干净吗? :

class SFTPProxy(object):
    def __init__(self, sftp):
        self.sftp = TRANSPORT.open_sftp_client()

    def __getattr__(self, item):
        if hasattr(self.sftp, item):
            return getattr(self.sftp, item)
        raise AttributeError(item)

这将相当迅速地处理各种属性:实例/类字段、实例/类/静态方法。

关于python - 如何动态代理类的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42043808/

相关文章:

python - 在 Pandas 数据框替换功能中使用正则表达式匹配组

python - redis python,hvals 结果作为生成器?

Python - 如何在不阻塞线程的情况下使用 FastAPI 和 uvicorn.run?

python - 在 python 中对一个大文件进行异或运算

python-2.7 - 类型错误:zip 参数 #1 必须支持迭代

python - Python (2.7) 可用的数据结构是否比标准库中的标准列表、集合、元组字典更多?

csv - 使用 python pandas 转置 csv 结构

python - 如何查找特定文件的路径

python - SortedListWithKey 的特征

python - 抓取特定文本的嵌套网页