Mixin features in python

Mixin features in python

 

After python supports multiple inheritance , can it support dynamic inheritance? In the program running process, redefine class inheritance. Python supports this dynamic inheritance. This is the mixin in python. In the process of defining the class, the inheritance order of the class is changed, and the class is inherited. When a module cannot be modified, the method of the class can be dynamically added through the mixin method, and the original inheritance system of the class can be dynamically changed. Understand multiple inheritance, mixin features are much simpler. But you need to pay attention to the changes in the specific inheritance system after mixin.

Copy code

#!/usr/bin/env python

import types

def MixIn(pyClass,mixInClass,makeAncestor=0):

    if makeAncestor:
        pyClass.__bases__ = (mixInClass,) + pyClass.__bases__
    elif mixInClass not in pyClass.__bases__:
        pyClass.__bases__ = pyClass.__bases__ + (mixInClass,)
    else:
        pass

class C1(object):
    def test(self):
        print 'test in C1'

class C0MixIn(object):
    def test(self):
        print 'test in C0MixIn'

class C2(C1,C0MixIn):
    def test(self):
        print 'test in C2'

class C0(C1):
    pass

if __name__ == "__main__":

    print C0.__mro__
    c1 = C0()
    c1.test()
    MixIn(C0,C0MixIn,1)
    c0 = C0()
    c0.test()
    print C0.__mro__

    print C2.__mro__
    MixIn(C2,C0MixIn)
    print C2.__mro__

Copy code

 

The results of the operation are as follows: python mixin2.py

Click (here) to collapse or open

Copy code

(<class '__main__.C0'>, <class '__main__.C1'>, <type 'object'>)
test in C1
test in C0MixIn
(<class '__main__.C0'>, <class '__main__.C0MixIn'>, <class '__main__.C1'>, <type 'object'>)
(<class '__main__.C2'>, <class '__main__.C1'>, <class '__main__.C0MixIn'>, <type 'object'>)
(<class '__main__.C2'>, <class '__main__.C1'>, <class '__main__.C0MixIn'>, <type 'object'>)

Copy code

 

Tags:  python

Guess you like

Origin blog.csdn.net/qq_42533216/article/details/112979916