有没有办法将父对象设置为特定实例?我有一个实用程序可以为我初始化一个复杂的对象,我想让它初始化一些对象以进行模拟。示例:
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) 创建父类的实例,但我只想将实例设置为工厂初始化的内容.
最佳答案
首先,这一行存在多个问题:
return super() = complexObject
- 您不能在
返回
内进行赋值(或任何其他语句),只能在表达式中进行。 - 您不能对函数调用的结果进行赋值,只能对可命名的目标(变量、对象的属性、列表中的索引等)进行赋值。
- 如果您可以对函数调用的结果进行赋值,那不会有任何用处。您只需将一些不可见的临时名称重新绑定(bind)到不同的值即可。
- 即使可以,
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)
关于Python 将父级设置为实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51827513/