如下所示,在 中twisted.spread.flavors.RemoteCache.unjellyFor
,我们创建了一个名为的虚拟对象cProxy
并将其返回给客户端代码的其余部分,而不是返回self
。
def unjellyFor(self, unjellier, jellyList):
if unjellier.invoker is None:
return setInstanceState(self, unjellier, jellyList)
self.broker = unjellier.invoker
self.luid = jellyList[1]
cProxy = _newDummyLike(self)
# XXX questionable whether this was a good design idea...
init = getattr(cProxy, "__init__", None)
if init:
init()
unjellier.invoker.cacheLocally(jellyList[1], self)
cProxy.setCopyableState(unjellier.unjelly(jellyList[2]))
# Might have changed due to setCopyableState method; we'll assume that
# it's bad form to do so afterwards.
self.__dict__ = cProxy.__dict__
# chomp, chomp -- some existing code uses "self.__dict__ =", some uses
# "__dict__.update". This is here in order to handle both cases.
self.broker = unjellier.invoker
self.luid = jellyList[1]
return cProxy
_newDummyLike 的主体如下所示:
def _newDummyLike(instance):
"""
Create a new instance like C{instance}.
The new instance has the same class and instance dictionary as the given
instance.
@return: The new instance.
"""
if isinstance(instance.__class__, type):
# New-style class
dummy = _DummyNewStyle()
else:
# Classic class
dummy = _Dummy()
dummy.__class__ = instance.__class__
dummy.__dict__ = instance.__dict__
return dummy
由于虚拟对象与“真实”对象cProxy
共享它的__dict__
和__class__
,因此我根本看不出制作虚拟对象的意义。为什么要创建假人?