Search code examples
pythonoopscalaabstract-class

Abstract attributes in Python


What is the shortest / most elegant way to implement the following Scala code with an abstract attribute in Python?

abstract class Controller {

    val path: String

}

A subclass of Controller is enforced to define "path" by the Scala compiler. A subclass would look like this:

class MyController extends Controller {

    override val path = "/home"

}

Solution

  • Python has a built-in exception for this, though you won't encounter the exception until runtime.

    class Base(object):
        @property
        def path(self):
            raise NotImplementedError
    
    
    class SubClass(Base):
        path = 'blah'