Mixins and Traits
Mixins in Python
Real use of mixins in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
# Author: Daniel R. Schlegel # Created: 4/11/2017 # A program demonstrating mixins with graph objects. class Label(object): def set_label(self,label): self.label = label def get_label(self): return self.label class Vertex(object): def __init__(self): pass class LabeledVertex(Label,Vertex): def __init__(self,label): self.set_label(label) class DirectedEdge(object): def __init__(self,source,target): self.source = source self.target = target class LabeledDirectedEdge(Label,DirectedEdge): def __init__(self,source,target,label): super(LabeledDirectedEdge,self).__init__(source,target) self.set_label(label) class Graph(object): def __init__(self,vertices,edges): self.vertices = vertices self.edges = edges def main(): v1 = LabeledVertex("V1") v2 = LabeledVertex("V2") e1 = LabeledDirectedEdge(v1,v2,"rel") g1 = Graph(set([v1, v2]),e1) # Now do something with g1... if __name__ == "__main__": main() |
Traits in Scala
Scala does not support multiple inheritance, but it does support “mixing in” any number of traits. Like Java 8 interfaces they allow for partial implementation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
trait WarpShip { var corePresent = true def ejectCore:Unit = {corePresent = false} def coreEjected:Boolean = !corePresent; def goToWarp(factor: Integer):Unit def exitWarp:Unit } class Starship extends WarpShip { var warpFactor = 0; def goToWarp(factor: Integer):Unit = {if(!coreEjected) warpFactor = factor} def exitWarp:Unit = {warpFactor = 0} } object Main { def main(args: Array[String]){ var enterprise = new Starship println("Warp " + enterprise.warpFactor); enterprise.goToWarp(5) println("Warp " + enterprise.warpFactor); enterprise.exitWarp enterprise.ejectCore enterprise.goToWarp(5) println("Warp " + enterprise.warpFactor); } } /* Output: * Warp 0 * Warp 5 * Warp 0 */ |
See the Scala documentation page for further details.