これは、既存のコードの修正を回避するための単なるスキームではありません。
これを行うには正当な理由があると思います.Luaで同様のことを行って、公開されたすべての関数のコードを実際に記述することなく、一部のCコードのラッパーを実装しました.
ただし、少なくとも実際のクラスをプロキシから分離する必要があります。
# the proxy maps attribute access to another object
class GetattrProxy(object):
def __init__(self, proxied, prefix=None):
self.proxied = proxied
self.prefix = prefix
def __getattr__(self, key):
attr = (key if self.prefix is None else self.prefix + '__' + key)
try:
# if the proxied object has the attr return it
return getattr(self.proxied, attr)
except AttributeError:
# else just return another proxy
return GetattrProxy(self.proxied, attr)
# the thing you want to wrap
class Target(object):
attr1__attr2__attr3 = 5
t = Target()
proxy = GetattrProxy(t)
print proxy.attr1.attr2.attr3
@katrielalex 提案:
class GetattrProxy2(GetattrProxy):
def __getattr__(self, key):
attr = (key if self.prefix is None else self.prefix + '__' + key)
proxy = GetattrProxy2(self.proxied, attr)
# store val only if the proxied object has the attribute,
# this way we still get AttributeErrors on nonexisting items
if hasattr(self.proxied, attr):
proxy.val = getattr(self.proxied, attr)
return proxy
proxy = GetattrProxy2(t)
proxy.attr1.val # 1
proxy.attr1.attr2.attr3.val # 5
proxy.attr1.attr2.val # raise AttributeError