Inspired by a great question (and bunch of great answers) from here.
Does the statement \"Code against an interface, not an object\" have any significance in Python?
An interface means you expect certain methods to be present and standardised across objects; that is the point of an interface or abstract base class, or whatever implementation you wish to consider.
For example (Java), one might have an interface for symmetric encryption like so:
public interface cipher
{
public void encrypt(byte[] block, byte[] key);
public void decrypt(byte[] block, byte[] key);
}
Then you can implement it:
public class aes128 implements cipher
{
public void encrypt(byte[] block, byte[] key)
{
//...
}
public void decrypt(byte[] block, byte[] key)
{
//...
}
}
It is then possible to declare an object like so:
cipher c;
What have we done here? Well, we've created this object c
whose type must match that of the interface. c
can refer to anything that matches this interface, so the next stage would be:
c = new aes128();
You can now call methods you expect a cipher
to have.
That's java. Now here's what you do in python:
class aes128(Object):
def __init__(self):
pass
def encrypt(self, block, key):
# here I am going to pass, but you really
# should check what you were passed, it could be
# anything. Don't forget, if you're a frog not a duck
# not to quack!
pass
When you want to use this, and you're not sure that the object you've been passed is, just try to use it:
c = aes128()
try:
c.encrypt(someinput, someoutput)
except:
print "eh? No encryption method?!"
Here, you're relying on c.encrypt's implementation to raise
if it can't handle what it has been passed, if the method exists. Of course, if c
is a string type and therefore not of the right type you require, it will also throw automatically, and you will catch (hopefully).
In short, one form of programming is typed such that you have to obey the interface rules, the other is saying you don't even need to write them down, you simply trust that if it didn't error, it worked.
I hope that shows you the practical difference between the two.