【发布时间】:2022-12-02 12:16:52
【问题描述】:
Preface: From my understanding the existing answers to this question assume control over the source or work around the problem.
Given a Super class, and MyClass which derives from it: How can an existing instance of a Super class be used as a base? The goal is to not call super().__init__() with fields from existing_super, but use the existing object. Similar to how in C++ a copy constructor would be used. Only MyClass can be adapted, Super has to remain unchanged.
class Super:
def __init__(self, constructed, by, the, super_factory):
\"\"\" no `existing_super` accepted \"\"\"
pass
class MyClass(Super):
def __init__(self, existing_super):
\"\"\" ????? \"\"\"
pass
s = super_factory()
mine = MyClass(s)
If this is not possible, would monkey patching Super help? What if Super uses/doesn\'t use slots?
标签: python inheritance constructor super
existing_superwas created and reproduce them. Unlike C++, inheritance only involves defining how attribute lookup occurs at runtime; it does not affect the actual construction of an object. (This is why, for example, you need to explicitly callsuper().__init__if you want the superclass initialization to occur.)Superwould be the correct place to define, say, a class method that takes an existing instance ofSuperand returns a new instance with the same details.Superconstruction\" is the crux of the problem. This is hidden bysuper_factory(), it createsSuper(..)with a lot of arguments and this logic (subject to change) should not be duplicated inMyClass.Super(..), which iterates over the__slots__to create a quasi copy constructor?