[Tutor] intefaces in python
Andre Engels
andreengels at gmail.com
Mon Jun 29 09:28:16 CEST 2009
On Sun, Jun 28, 2009 at 5:00 PM, Amit Sethi<amit.pureenergy at gmail.com> wrote:
> Hi , I don't suppose python has a concept of interfaces. But can somebody
> tell me if their is a way i can implement something like a java interface
> in python.
Sure. Interfaces are just Java's compensation for not having multiple
inheritance. Python does have multiple inheritance, so that's what one
would use. Although one could also use duck typing, and then use
'nothing' as an implementation...
More specific:
========================
Java Interface:
public interface MyInterface {
string doSomething(string line);
string doSomethingElse(string line);
}
Java Implementation:
public class MyImplementation {
string doSomething(string line) {
return "I did something with" + line;
}
string doSomethingElse(string line) {
return "I did something else."
}
}
==============================
Python Interface:
class MyInterface(object):
doSomething(line):
raise NotImplementedError
doSomethingElse(line):
raise NotImplementedError
Python Implementation:
class MyImplementation(MyInterface):
doSomething(line):
return "I did something with "+line
doSomethingElse(line):
return "I did something else."
==============================
Python interface using duck typing:
# Hey guys, when you call something a 'MyInterface', it needs methods
doSomething and doSomethingElse
Python Implementation using duck typing:
class MyImplementation(object):
# These things implement MyInterface
doSomething(line):
return "I did something with "+line
doSomethingElse(line):
return "I did something else."
--
André Engels, andreengels at gmail.com
More information about the Tutor
mailing list