如何动态代理类的方法?

2024-10-06 08:13:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用以下代码代理类的“all”方法:

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)

当我像这样调用方法时:

^{pr2}$

它起作用了。在

当我像这样调用方法时:

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

程序挂起了,代码中有什么浅显的问题吗?在


Tags: the方法代码importselfparamiko代理def
1条回答
网友
1楼 · 发布于 2024-10-06 08:13:37

我在您的方法中看到的一个问题是,type(self.sftp).__dict__中的值并非都是函数。因此,y(...)将失败。重写^{}不是更简单更干净吗:

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)

这将相当迅速地处理所有类型的属性:实例/类字段、实例/类/静态方法。在

相关问题 更多 >