如果你想在其他地方露出原有的特性,你可以定義一個包裝類:
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'
這很可能是某些事情留他們的方式。結束使用真實的東西,而不是模擬。 – Oleksiy 2012-09-19 00:40:47