Python "implements <interface>" equivalent?

Wojciech Gryc wojciech at gmail.com
Thu Oct 4 11:29:01 EDT 2007


Thank you Carl and thank you Jarek. This makes me feel much better --
on to coding, I shall go. :)

Thanks again,
Wojciech

On Oct 4, 11:27 am, Carl Banks <pavlovevide... at gmail.com> wrote:
> On Oct 4, 11:11 am, Wojciech Gryc <wojci... at gmail.com> wrote:
>
> > Hi,
>
> > I recently started using Python and am extremely happy with how
> > productive it's made me, even as a new user. I'm hoping to continue
> > using the language for my research, and have come across a bit of a
> > stumbling block.
>
> > I'm a seasoned Java programmer and quite a big fan of interfaces...
> > i.e. The idea that if I make a number of distinct classes that
> > implement interface X, I can pass them all as parameters to functions
> > or whatnot that require an X object.
>
> > Is there something similar in Python?
>
> Yes: you do it pretty much the same way you'd do it in Java, except
> for two differences:
> * leave out the "implements Interface" part
> * don't actually create an Interface class
>
> And then, voila!, you can write functions that can accept any class
> that implements your interface.
>
> > What I'd like to do is create a feature detection system for my work
> > -- specifically, a general class / interface called "Feature" and then
> > subclasses that implement functions like isFeaturePresent() in all of
> > their different and unique ways. I'd love to hear how I can do this in
> > Python.
>
> Just define isFeaturePresent() in any class you want.  That's all you
> have to do; any class that defines this method can be passed to any
> function that invokes it, without having to "implement" or "subclass"
> anything.
>
> This is known as "duck typing" in Python lingo.
>
> Carl Banks





More information about the Python-list mailing list