Home > other >  Inherit only the type from parent class in Python
Inherit only the type from parent class in Python

Time:03-17

Consider a parent class Foo and my class myFoo. I want that isinstance(myFoo, Foo) returns True, but without inheriting all the methods and attributes from Foo.

e.g.

class Foo:
    def __init__(self):
        # do stuff

    # tons of methods!

class myFoo:
    def __init__(self):
         # do stuff

    # couple of methods not in common with Foo

This is probably a niche use case, but it would be very handy for me. How can I 'fool' isinstance in believing that myFoo is a Foo instance without doing class myFoo(Foo) and thus inheriting the tons of methods from Foo.

Edit with context:

So in my case, Foo inherits from Mixin classes, each defining a bunch of related methods. Several of the methods defined in those Mixin start with self if isinstance(self, Foo) else self.foo because either Foo is provided, or a class with Foo set as a .foo attribute is provided.

Now, I want to define a different myFoo class which inherits only some of those Mixin. But they do not work as they check isinstance(self, Foo). Changing the Mixin or the Foo class is not an option, so either I have to copy the entire Mixin and all the functions it might call and edit them; or I find a way to 'fool' the Mixin in believing that what I provide to it is indeed a Foo instance.


Alternatively, I could inherit from Foo and overwrite/raise AttributeError on calls to all the methods I do not want as part of myFoo.

CodePudding user response:

Sounds like a gross violation of https://en.wikipedia.org/wiki/Liskov_substitution_principle. Maybe you could extract a superclass that had the interface that you want and then have both classes inherit from it.

CodePudding user response:

Code:

class Trickster(type):
    def mro(cls):
        return super().mro()   [Foo]


class Foo:
    pass


class Bar(metaclass=Trickster):
    pass


print(isinstance(Bar(), Foo))

Result:

True
  • Related