我有班级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 objectbut 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)更多推荐
发布评论