What is a mixin, and why are they useful?

后端 未结 16 2122
無奈伤痛
無奈伤痛 2020-11-22 00:18

In \"Programming Python\", Mark Lutz mentions \"mixins\". I\'m from a C/C++/C# background and I have not heard the term before. What is a mixin?

Reading between the

16条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 01:17

    mixin gives a way to add functionality in a class, i.e you can interact with methods defined in a module by including the module inside the desired class. Though ruby doesn't supports multiple inheritance but provides mixin as an alternative to achieve that.

    here is an example that explains how multiple inheritance is achieved using mixin.

    module A    # you create a module
        def a1  # lets have a method 'a1' in it
        end
        def a2  # Another method 'a2'
        end
    end
    
    module B    # let's say we have another module
        def b1  # A method 'b1'
        end
        def b2  #another method b2
        end
    end
    
    class Sample    # we create a class 'Sample'
        include A   # including module 'A' in the class 'Sample' (mixin)
        include B   # including module B as well
    
        def S1      #class 'Sample' contains a method 's1'
        end
    end
    
    samp = Sample.new    # creating an instance object 'samp'
    
    # we can access methods from module A and B in our class(power of mixin)
    
    samp.a1     # accessing method 'a1' from module A
    samp.a2     # accessing method 'a2' from module A
    samp.b1     # accessing method 'b1' from module B
    samp.b2     # accessing method 'a2' from module B
    samp.s1     # accessing method 's1' inside the class Sample
    

提交回复
热议问题