Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: An object constructor calls itself

I have encountered the following code. An object constructor calls itself:

  class StatusMixin(object):
    def __init__(self):
        super(StatusMixin, self).__init__()

        self.does_something()

Is there any practical reason why it is implemented like this? I think people use thesuper method only in the context of multiple inheritance.

like image 960
musthero Avatar asked Jan 24 '26 20:01

musthero


1 Answers

You mention multiple inheritance. This class is described as a mixin: that is, it's specifically intended to be used in the case of multiple inheritance. It will be one of the elements in a class hierarchy, but not the top or the bottom. That's why it calls super - the next item in the method resolution order will not in practice be object, but some other class.

Consider this hierarchy:

class Super(object):
    pass

class Sub(StatusMixin, Super)
    pass

and examine Sub.mro():

[__main__.Sub, __main__.StatusMixin, __main__.Super, object]

So you see that here the result of the super call in StatusMixin is not object at all, but Super.

like image 72
Daniel Roseman Avatar answered Jan 29 '26 20:01

Daniel Roseman