How do Java interfaces translate to Python?
Martin von Loewis
loewis at informatik.hu-berlin.de
Mon Oct 1 11:01:01 CEST 2001
Gordon Tyler <gordon at doxxx.net> writes:
> > What exactly is it that you do with interfaces in Java?
> Enforcing a contract between objects, i.e. if you want to work with this
> object, your object must implement this interface.
> I suppose the thing I'm really missing is compile-time type safety.
If you want compile-time things to fail if an object isn't
implementing an interface, then no, Python has no equivalent of that.
If you want to make runtime assertions on interfaces, then you can do
it like this:
_interfaces = ['IFoo','IBar']
def implements(self, _if):
return (_if in self._interfaces) or Base.implements(self, _if)
foo = Foo()
Of course, this does only allows a runtime check that the class
declares that it has the interface, not that the class actually
implements the interface.
This is like Java: even though the compiler can check whether the
class implements all operations of the interface, it cannot verify
whether all these implementations follow the interface contract (which
may include invariants like "\forall x:foo.push(x);foo.pop() is x", or
More information about the Python-list