Reputation: 1520
The typical way to do subclassing in Python is this
class Base:
def __init__(self):
self.base = 1
class Sub(Base):
def __init__(self):
self.sub = 2
super().__init__()
And this allows me to create an instance of type Sub that can access both base
and sub
properties.
However, I'm using an api that returns a list of Base
instances, and I need to convert each instance of Base
into an instance of Sub
. Because this is an API that is subject to change, I don't want to specifically unpack each property and reassign them by hand.
How can this be done in Python3?
Upvotes: 0
Views: 100
Reputation: 6056
You can use *args
and **kwargs
if you don't want to hard code the name of the arguments.
class Base:
def __init__(self, a, b, c="keyword_arg"):
self.a = a
self.b = b
self.c = c
class Sub(Base):
def __init__(self, *args, **kwargs):
self.sub = 2
super().__init__(*args, **kwargs)
bases = [Base(1, 2, "test") for _ in range(10)]
subs = [Sub(**b.__dict__) for b in bases]
Note that this assumes that all the properties of Base
is given as arguments to the Base
.
Upvotes: 1