Productively Distracted
Posted Friday April 22, 2011 around 10:28 PM

I have been using scala a lot recently. One of my favorite things about it is traits. Traits are basically class interfaces (think java and c#) that can contain code and be mixed in with classes or other traits. In python we have had this functionality for a long time. Here is a very contrived example in scala:

trait Output {
  def getFormat: String
  def say(msg: String) { println(getFormat.format(msg)) }
}

object MyClass extends Output {
  def getFormat = "$: %s"
  def doWork() { (0 until 5).foreach(i => say(i.toString)) }
}

MyClass.doWork()
Download

Which will output:

$ scala test.scala
$: 0
$: 1
$: 2
$: 3
$: 4
Download

Now in python we use the abc module to make the get_format() method required and the Output class abstract which provides the same functionality:

import abc

class Output(object):
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    def get_format(self):
        pass

    def say(self, msg):
        print self.get_format() % msg

class MyClass(Output):
    def get_format(self):
        return "$: %s"

    def do_work(self):
        for i in range(5):
            self.say(i)

tester = MyClass()
tester.do_work()
Download

Output is:

$ python test.py
$: 0
$: 1
$: 2
$: 3
$: 4
Download

Not ground breaking or even complicated, but still handy in the right situation.

blog comments powered by Disqus