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?

7
  • I'm not sure if I understand correctly but why don't you use *args and **kwargs? Commented May 21, 2020 at 20:07
  • 1
    Does this answer your question? How to convert (inherit) parent to child class? Commented May 21, 2020 at 20:09
  • @Asocia Sounds like you have a solution, feel free to answer the question. Commented May 21, 2020 at 20:09
  • @PM77-1 It doesn't look like it. Commented May 21, 2020 at 20:11
  • 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! Commented May 21, 2020 at 20:24

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.