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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With