0

I have a class foo that inherits from bar. However I also want to have the option when initializing foo to have it inherit from wall instead of bar. I am thinking something like this:

class Foo():
    def __init__(self, pclass):
        self.inherit(pclass)
        super().__init__()

Foo(Bar) # child of Bar
Foo(Wall) # child of Wall

Is this possible in Python?

6
  • "Is this possible in Python?" – What happened when you tried it? Commented Aug 25, 2018 at 22:27
  • Well I dont think self.inherit is a defined method so this would throw an error. I'm asking if there is a function like self.inherit that would take in an arbitrary class and then inherit that class Commented Aug 25, 2018 at 22:31
  • 1
    It is technically possible. But it’s something obscure and very unusual. Can you explain your use-case? Commented Aug 25, 2018 at 22:33
  • 1
    That’s not the way to do this. All you need is to not use inheritance at all and just setup the GUI by passing your window as argument. Which allows for your usecase and is idiomatic. Commented Aug 25, 2018 at 22:43
  • 1
    If you really wanted to do this, since Foo(Bar) and Foo(Wall) give you instances of different types, and those types don't exist statically, you have to create them on the fly. Which means you have to do this in __new__ instead of __init__. For example, class subcls(cls, pclass): pass, then return super().__new__(subcls). But I don't know what that buys you over a more idiomatic design, except for extra cleverness that makes your code harder to understand. Commented Aug 25, 2018 at 22:57

1 Answer 1

3

It's not really possible easily, because classes are defined at the time of executing the class block, not at the time of creating an instance.

A popular design pattern to use instead would be to put the common code into a mixin:

class FooMixin:
    # stuff needed by both Foo(Bar) and Foo(Wall)

class FooBar(FooMixin, Bar):
    ...

class FooWall(FooMixin, Wall):
    ...

Then you can use some sort of factory function:

def make_foo(parent, *init_args, **init_kwargs):
    if parent is Bar:
        Foo = FooBar
    elif parent is Wall:
        Foo = FooWall
    return Foo(*init_args, **init_kwargs)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.