与继承共享基础对象(Sharing base object with inheritance)

编程入门 行业动态 更新时间:2024-10-26 03:21:51
与继承共享基础对象(Sharing base object with inheritance)

我有班级Base 。 我想在Derived类中扩展它的功能。 我打算写:

class Derived(Base): def __init__(self, base_arg1, base_arg2, derived_arg1, derived_arg2): super().__init__(base_arg1, base_arg2) # ... def derived_method1(self): # ...

有时我已经有了一个Base实例,我想基于它创建一个Derived实例,即一个共享Base对象的Derived实例(不会从头开始重新创建它)。 我以为我可以编写一个静态方法来做到这一点:

b = Base(arg1, arg2) # very large object, expensive to create or copy d = Derived.from_base(b, derived_arg1, derived_arg2) # reuses existing b object

但似乎不可能。 或者我错过了一种方法来完成这项工作,或者(更有可能)我错过了一个很大的原因,为什么它不能被允许工作。 有人可以解释它是哪一个吗?

[当然,如果我使用的是组合而不是继承,那么这一切都很容易。 但我希望通过__getattr__避免将所有Base方法委托给Derived 。

I have class Base. I'd like to extend its functionality in a class Derived. I was planning to write:

class Derived(Base): def __init__(self, base_arg1, base_arg2, derived_arg1, derived_arg2): super().__init__(base_arg1, base_arg2) # ... def derived_method1(self): # ...

Sometimes I already have a Base instance, and I want to create a Derived instance based on it, i.e., a Derived instance that shares the Base object (doesn't re-create it from scratch). I thought I could write a static method to do that:

b = Base(arg1, arg2) # very large object, expensive to create or copy d = Derived.from_base(b, derived_arg1, derived_arg2) # reuses existing b object

but it seems impossible. Either I'm missing a way to make this work, or (more likely) I'm missing a very big reason why it can't be allowed to work. Can someone explain which one it is?

[Of course, if I used composition rather than inheritance, this would all be easy to do. But I was hoping to avoid the delegation of all the Base methods to Derived through __getattr__.]

最满意答案

依靠你的Base类使用base_arg1 , base_arg2做的base_arg2 。

class Base(object): def __init__(self, base_arg1, base_arg2): self.base_arg1 = base_arg1 self.base_arg2 = base_arg2 ... class Derived(Base): def __init__(self, base_arg1, base_arg2, derived_arg1, derived_arg2): super().__init__(base_arg1, base_arg2) ... @classmethod def from_base(cls, b, da1, da2): return cls(b.base_arg1, b.base_arg2, da1, da2)

Rely on what your Base class is doing with with base_arg1, base_arg2.

class Base(object): def __init__(self, base_arg1, base_arg2): self.base_arg1 = base_arg1 self.base_arg2 = base_arg2 ... class Derived(Base): def __init__(self, base_arg1, base_arg2, derived_arg1, derived_arg2): super().__init__(base_arg1, base_arg2) ... @classmethod def from_base(cls, b, da1, da2): return cls(b.base_arg1, b.base_arg2, da1, da2)

更多推荐

本文发布于:2023-07-15 18:54:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1117495.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   基础   Sharing   inheritance   object

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!