用parent初始化子类

Pro*_*e85 5 python inheritance

有父类和子类我想用父实例初始化子类.我的方式看起来很麻烦(见下文):

我定义了一个static方法来提取init父初始化的参数:

class Parent(object):
    @staticmethod
    get_init_params(parent_obj):
        a = parent_obj.a
        b = parent_obj.b
        return (a, b)

    def __init__(self, a, b):
        self.a = a
        self.b = b

class Child(Parent):
    def __init__(self, parent):
        super(Parent, self).__init__(*get_init_params(parent))
Run Code Online (Sandbox Code Playgroud)

可能有更直接的方式吗?

编辑现在课程更简单

che*_*ner 6

我想你想的概念分开intializing一个Child从概念对象创建一个从Parent.这get_init_params只是增加了一层你不需要的复杂性; 直接访问属性.

class Child(Parent):
    @classmethod
    def from_parent(cls, parent):
        return cls(parent.a, parent.b)

    def __init__(self, a, b):
        super(Child, self).__init__(a, b)
        # Note: the fact that yo have to do this,
        # or not call the parent's __init__ in the first
        # place, makes me question whether inheritance
        # is the right tool here.
        self.a = revert_change(self.a)
        self.b = revert_change(self.b) 

p = Parent(3, 5)
c1 = Child.from_parent(p)
c2 = Child(6, 6)
Run Code Online (Sandbox Code Playgroud)

如果对从父级获取的值进行更改,请to_parent在创建Child对象之前应用它们.

def from_parent(cls, parent):
    return cls(revert_change(parent.a), revert_change(parent.b))
    # Or, if you save the original values
    # return cls(parent.orig_a, parent.orig_b)
Run Code Online (Sandbox Code Playgroud)