如果你想在别处暴露原始属性,你可以定义一个包装类:
class OverrideAttributePath(object):
"""A proxy class where we override a specific attribute path with the
value given. For any other attribute path, we just return
attributes on the wrapped object.
"""
def __init__(self, thing, path, value):
self._thing = thing
self._path = path
self._value = value
def __dir__(self):
return dir(self._thing)
def __len__(self):
return len(self._thing)
def __getitem__(self, index):
if self._path == [index]:
return self._value
elif self._path[0] == index:
return OverrideAttributePath(
self._thing[index], self._path[1:], self._value)
else:
return self._thing[index]
def __getattr__(self, key):
if self._path == [key]:
return self._value
elif self._path[0] == key:
return OverrideAttributePath(
getattr(self._thing, key), self._path[1:], self._value)
else:
return getattr(self._thing, key)
那么用法如下:
>>> r = Foo(x,y)
>>> r2 = OverrideAttributePath(r, ['prop_a', 'prop_b', 'prop_c'], 'my_fish')
>>> r2.prop_a.prop_b.prop_c
'my_fish'