是否可以将父对象设置为特定实例?我有一个实用程序,可以为我初始化一个复杂的对象,我想将其初始化为一些对象以进行模拟。示例:
class ComplexObject:
def __init__(arg1, arg2, arg3):
#do some stuff
return
class ComplexObject_Mock(ComplexObject):
def __init__():
complexObject = ComplexObjectFactory.NewComplexObject()
return super() = complexObject
现在,由于最后一行,我知道上述方法不起作用。通常,我使用super().__init(arg1, arg2, arg3)
创建父类的实例,但我想将其设置为工厂初始化的值。
答案 0 :(得分:1)
首先,此行存在多个问题:
return super() = complexObject
return
内执行赋值(或其他任何语句),只能执行一个表达式。super()
也会返回一个特殊的魔术代理对象,因此,如果强制它返回不知道如何像super
一样工作的其他对象,则会破坏一切。super()
返回的是self
的代理。如果您以某种方式使其成为完全不相关的对象的代理,那么您在super()
上调用的每个方法最终都将访问和变异该完全不相关的对象的属性,这对self
无效。此外,__init__
是一种常规方法,需要self
或无法调用。
同时,如果您要更改对象的创建方式,而不仅仅是初始化对象的方式,则必须使用__new__
,而不是__init__
。
最后,模拟的全部目的是您不必创建ComplexObject
;您正在创建的行为就像 而不是 一样,因此整个事情从一开始就没有多大意义。
这是一个疯狂的猜测,但是我认为您真正想得到的是拥有一个ComplexObject
的代理对象,并且还伪造了一,委派一些电话并自行处理其他电话。换句话说:
class ComplexObject_Mock(ComplexObject):
def __init__(self):
self.complexObject = ComplexObjectFactory.NewComplexObject()
def method_to_delegate(self, arg):
# instead of return super().method_to_delegate(arg)
return self.complexObject.method_to_delegate(arg)
def method_to_steal(self, arg):
# don't call self.complexObject.method_to_steal
# just as you wouldn't have called super().method_to_steal
def method_to_hook(self, arg):
arg = self._preprocess(arg)
# instead of result = super().method_to_hook(arg)
result = self.complexObject.method_to_hook(arg)
return self._postprocess(result)