我想代理"所有"使用以下代码的类的方法:
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
程序刚刚挂起,代码中是否有任何浅层问题?
答案 0 :(得分:1)
我可以通过您的方法看到的一个问题是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)
这将很快处理所有类型的属性:实例/类字段,实例/类/静态方法。