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()
Which will output:
$ scala test.scala
$: 0
$: 1
$: 2
$: 3
$: 4
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()
Output is:
$ python test.py
$: 0
$: 1
$: 2
$: 3
$: 4
Not ground breaking or even complicated, but still handy in the right situation.