【问题标题】:Initialize a superclass with an existing object (copy constructor)Initialize a superclass with an existing object (copy constructor)
【发布时间】: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?

  • You\'ll have to know the details of how existing_super was 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 call super().__init__ if you want the superclass initialization to occur.)
  • It would be good if you could include a couple of example fields from Super to give an impression of what work MyClass has to do.
  • And as such, Super would be the correct place to define, say, a class method that takes an existing instance of Super and returns a new instance with the same details.
  • @chepner Indeed, \"know the details of Super construction\" is the crux of the problem. This is hidden by super_factory(), it creates Super(..) with a lot of arguments and this logic (subject to change) should not be duplicated in MyClass.
  • So a (monkey patched?) class method inside Super(..), which iterates over the __slots__ to create a quasi copy constructor?

标签: python inheritance constructor super


【解决方案1】:
猜你喜欢
  • 2022-12-01
  • 2022-12-27
  • 1970-01-01
  • 2022-11-20
  • 1970-01-01
  • 1970-01-01
  • 2021-12-07
  • 2016-08-21
  • 1970-01-01
相关资源
最近更新 更多