Python "implements <interface>" equivalent?

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Thu Oct 4 19:05:31 CEST 2007


Wojciech Gryc a écrit :
> 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

So you may want to read this:

http://dirtsimple.org/2004/12/python-is-not-java.html

http://dirtsimple.org/2004/12/java-is-not-python-either.html

> 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, and it's even simpler : just pass your object. If it effectively 
implements the desired interface, everything will work fine !-)

IOW : Python is dynamically typed, there's no parameters type 
declaration and no parameters type checking at compile time - so you 
just don't need to tell the compiler that your class implements a given 
interface. Anyway, this would be a waste of time since you can 
add/delete/replace attributes and methods at runtime either on a 
per-class or per-instance basis.

> 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.

I'm not sure about what you exactly want to do, but FWIW, checking if an 
object has a given attribute is quite simple:

if has_attr(obj, 'attribute_name'):
   print "Hurray"
else:
   print "D'oh"

Note that in Python, methods are attributes too - only they are callable.



> Thanks,
> Wojciech
> 



More information about the Python-list mailing list