代码之家  ›  专栏  ›  技术社区  ›  Jamie Marshall

Python将父对象设置为实例

  •  1
  • Jamie Marshall  · 技术社区  · 7 年前

    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)

    1 回复  |  直到 7 年前
        1
  •  1
  •   user2357112    7 年前

    首先,这条线存在多个问题:

    return super() = complexObject
    
    • 不能在内部执行赋值(或任何其他语句) return ,只是一个表达。
    • 不能对函数调用的结果赋值,只能对可命名的targeta变量、对象的属性、列表中的索引等赋值。
    • 如果可以对函数调用的结果进行赋值,那就没有任何用处了。您只需将一些不可见的临时名称重新绑定到另一个值。
    • 即使你可以, super() 返回一个特殊的魔法代理对象,因此强制它返回一些不知道如何像代理一样工作的其他对象 super
    • 最后,什么 超级() returns是 self . 如果您以某种方式将它变成一个完全无关的对象的代理,那么您调用的每个方法 最终将访问和修改完全无关对象的属性,这对 .

    也, __init__ 是一种正常的方法,需要 自己 或者它不能被称为。

    __new__ __初始化__

    最后,嘲弄的重点是你 不要 ComplexObject ; 你在创造一些 行为 像一个没有 存在

    真正地 这里需要一个代理对象 拥有 A. 络合对象 ,也假装是一个,授权一些电话,自己处理其他电话。换言之:

    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)