About inheritance behavior

class Parent:
    def __init__(self, *args, **kwargs):
        print(args, kwargs)


p = Parent()


class Child(p):
    pass


print(Child)
child = Child()

Am I screwing the way inheritance works? I was so curious what happens if I pass an object or something else other than a class, inside Child(...) then I understand something it works behind the scene was like Child(ParentClassName). type('Child', (ParentClassName,), {...: ..., ...})
the behavior is getting things different when trying to pass something other than a class. It would be nice if it raises an Error so it never happens accidentally at any point of time something like this.

if isinstance(ParentClassName, type):
    ...
else:
    raise Error("Inheritance must be of classes not with an object")

I found this when I was practicing OOP if my consideration is wrong tell me whether it is intended behavior?

CPython versions tested on:

3.11

Operating systems tested on:

Windows

Your Parent class here is behaving like a metaclass. Normally you’d want those to subclass type, but as you’ve found here, that isn’t actually mandated.

Have fun with the incredibly dynamic nature of Python :slight_smile:

Classes must inherit from other classes, but you aren’t restricted to using only instances of type in the list of base classes in a class statement. You can provide any callable object that has a __mro_entries__ method that returns a tuple of real classes. For example,

class A: pass
class B: pass

class Fake:
    def __init__(self, *args, **kwargs):
        print(f"Creating a base-class factory with args {args} and keyword args {kwargs}")

    def __mro_entries__(self, bases):
        print(f"Replacing {bases} with {(A, B)}")
        return (A, B)

fakeclass = Fake(1, 2, c=3)

class Foo(fakeclass):
    pass

assert issubclass(Foo, A) and issubclass(Foo, B)
2 Likes

__mro_entries__() something that I’ve learned new ThankYou so much and if you don’t mind can you tell me where can I find more details on that dunder method?

The link is to the documentation for __mro_entries__ specifically, but the entire Data Model section of the language reference is a good read.

1 Like