I want to create lightweight interfaces with methods that I can plug into classes. Here is an short example in Scala:
class DB {
def find(id: String) = ...
}
trait Transformation extends DB {
def transform(obj: String): String
override def find(id: String) =
transform(super.find(id))
}
trait Cache extends DB {
val cache = Cache()
override def find(id: String) = {
...
if (cache.contains(id))
cache.find(id)
else {
cache.set(id, super.find(id))
cache.get(id)
}
}
}
With these classes (traits) we can instantiate DB classes with Transformation, with Cache, or both. Note that Transformation has an abstract method transform, which still needs to implemented in concrete classes.
new DB() with Transformation {
def transform(obj: String): obj.toLower()
}
new DB() with Cache
new DB() with Transformation with Cache {
def transform(obj: String): obj.toLower()
}
Is there any way to achieve something like this in Python? I know there exists a Traits package for Python, but its purpose seems to be different.