0

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?

DeepDeadpool
  • 1,441
  • 12
  • 36
  • I'm not sure if I understand correctly but why don't you use `*args` and `**kwargs`? – Asocia May 21 '20 at 20:07
  • 1
    Does this answer your question? [How to convert (inherit) parent to child class?](https://stackoverflow.com/questions/10030412/how-to-convert-inherit-parent-to-child-class) – PM 77-1 May 21 '20 at 20:09
  • @Asocia Sounds like you have a solution, feel free to answer the question. – DeepDeadpool May 21 '20 at 20:09
  • @PM77-1 It doesn't look like it. – DeepDeadpool May 21 '20 at 20:11
  • So the base objects are already instantiated? – jordanm May 21 '20 at 20:19
  • @jordanm yes. The API returns a list of Base instances. – DeepDeadpool May 21 '20 at 20:20
  • 2
    You'll need to write a function that knows how to turn a `Base` object into a `Sub` object. Perhaps this can be done in `Sub.__init__` or perhaps you write a class method in `Sub` that knows how. Or even just a stand-alone function. Alternately, perhaps `Sub` shouldn't inherit from `Base` at all and just do composition by keeping a `Base` member variable. Lots of choices! – tdelaney May 21 '20 at 20:24

1 Answers1

1

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.

Asocia
  • 5,935
  • 2
  • 21
  • 46