我想使用以下代码代理一个类的“所有”方法:
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/