Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialize child class with parent

Having a parent and a child class I would like to initialize the child class with a parent instance. My way seems very cumbersome (see below):

I define a staticmethod to extract init parameters for parent initialization:

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))

Is there possibly a more direct way?

EDIT now the classes are simpler

like image 741
ProfHase85 Avatar asked May 07 '15 15:05

ProfHase85


1 Answers

I think you want to separate the notion of intializing a Child object from the notion of creating one from a Parent. The get_init_params is just adding a layer of complexity you don't need; access the attributes directly.

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)

If there are changes to make to the values you get from the parent, apply them in to_parent before creating the Child object.

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)
like image 67
chepner Avatar answered Sep 27 '22 17:09

chepner