David Boshton David Boshton - 1 year ago 96
Python Question

How to call super of enclosing class in a mixin in Python?

I have the following code, in Django:

class Parent(models.Model):
def save(self):
# Do Stuff A

class Mixin(object):
def save(self):
# Do Stuff B

class A(Parent, Mixin):
def save(self):
super(A, self).save()
# Do stuff C

Now, I want to use the mixin without blatting the behaviour of the save in Parent. So I when I save, I want to do stuff C, B, and A. I've read Calling the setter of a super class in a mixin however I don't get it and having read the super docs it doesn't seem to answer my question.

THe question is, what do I put in the mixin to make sure it does stuff B and doesn't stop Stuff A from happening?

Answer Source

How about calling super in your mixin class?

class Parent(object):
    def test(self):

class MyMixin(object):
    def test(self):
        super(MyMixin, self).test()

class MyClass(MyMixin, Parent):
    def test(self):
        super(MyClass, self).test()

if __name__ == "__main__":
    my_obj = MyClass()

This will give you the output as:

$ python test.py
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download