473,413 Members | 2,053 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,413 software developers and data experts.

classes and interfaces

hi
i come from a non OO environment. now i am learning about classes. can
i ask, in JAva, there are things like interface. eg
public interface someinterface {
public somemethod ();
....
...
}

In python , how to implement interface like the above? is it just
define a class??

class someinterface:
def somemethod: blah....

thanks

Jun 27 '06 #1
6 1806
s9************@yahoo.com wrote:
hi
i come from a non OO environment. now i am learning about classes. can
i ask, in JAva, there are things like interface. eg
public interface someinterface {
public somemethod ();
....
...
}

In python , how to implement interface like the above? is it just
define a class??


Java interfaces are a workaround the combination of static typing
(limiting polymorphism) and lack of multiple inheritance. Since Python
is dynamically typed (polymorphism does not depend on type), there's no
such need:

class Foo(object):
def doThis(self):
print "in Foo.doThis"

class Bar(object):
def doThis(self):
print "in Bar.doThis"

def doIt(obj):
obj.doThis()

f = Foo()
b = Bar()

doIt(f)
doIt(b)

A you can see, doIt() works for any object having a doThis() method. No
need for inheritance or interface here.

Note that we do have something like interfaces (in some third-part
librairies), but with a somewhat different (and much more powerful) usage:

http://peak.telecommunity.com/protocol_ref/ref.html

But if you're new to OO, this may not be the best starting point !-)

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jun 27 '06 #2
<s9************@yahoo.com> wrote in message
news:11**********************@x69g2000cwx.googlegr oups.com...
hi
i come from a non OO environment. now i am learning about classes. can
i ask, in JAva, there are things like interface. eg
public interface someinterface {
public somemethod ();
....
...
}

In python , how to implement interface like the above? is it just
define a class??

class someinterface:
def somemethod: blah....

thanks


This question crops up every week or two on this list. (This is a healthy
indicator of people looking to map their Java learnings to Python. Some of
the best programming knowledge I've gained has come from comparing features
among different languages, and understanding their respective
purposes/strengths/shortcomings. In this case, presence of interfaces in
Java) Here are some recent threads that cover this topic:

http://groups.google.com/group/comp....411c8c9322821c

http://groups.google.com/group/comp....411c8c9322821c
Is this in the FAQ? Hmm, these two FAQ's may be related to your question
(although you have to know what you're looking for to recognize them):
http://www.python.org/doc/faq/genera...spec-in-python
http://www.python.org/doc/faq/progra...tatic-analysis
Lastly, you should look into
Jun 27 '06 #3
"Paul McGuire" <pt***@austin.rr._bogus_.com> wrote in message
news:ZO******************@tornado.texas.rr.com...

Lastly, you should look into


.... this blog post: http://dirtsimple.org/2004/12/python-is-not-java.html,
and its partner http://dirtsimple.org/2004/12/python-is-not-java.html.

Unfortunately, many who ask "How do I implement a Java interface in Python?"
are met with some defensiveness on this list, as if the OP is asking "What's
wrong with stupid Python language that it doesn't have something as basic as
interfaces?". Sometimes this is attitude on the OP's part, sometimes just
presumption on the part of the various readers. Some responses are of an
indignant "Interfaces? We don't need no stinkin' interfaces!" variety -
unfortunately, most of these shed more heat than light to the discussion,
usually omitting the important details as to *why* Python don't need those
malodorous code devices.

Java uses interfaces for two purposes:
1. to enforce at compile time whether a particular class implements a set of
methods, and correspondingly enforce that only instances of such classes are
permitted as arguments to functions/methods that declare arguments to be of
the interface type
2. as a workaround for not directly supporting multiple inheritance

Informally (and in design practices such as UML class diagrams), interfaces
also serve to document expected class capabilities - which in the case of
Java and C++, have the added support of compile-time checking to verify the
class contains methods corresponding to those in the interface. Note that
I've been careful *not* to imply that Java classes that pass this
compile-time check actually *implement* the interface, as is often assumed.
The only thing one knows for sure when Java accepts a class as being an
interface implementer is that the class provides all the corresponding
method definitions - but it cannot know if all expectations of behavior and
pre- and post-conditions are actually implemented within those methods.
While compile-time checking is a decent crutch 95% of the time, it will
never catch errors like this:

int passBackSomethingImportant() {
// be sure to come back and implement this before production
release!
return 0;
}

Very few "how do I implement Java interfaces in Python" posters ever get
specific about which purpose they are trying to address with their Python
interface renditions. It is entirely possible that the posters don't *know*
why the interface is there, they are just trying to directly port some Java
code to Python.

So specifically:
1. Python does not do any compile-time enforcement of method implementations
in classes of objects. While some think this is like trapeze flying without
a net, Pythoneers will reply that the net is a false assurance anyway (based
on the example I show above). So to "port" this type of interface, the only
thing to do is, well, ignore the interface - Python really doesn't require
it. You *could* create a class such as:

class ISomethingOrOther:
def whatSomethingsDo(blah, blah2):
raise NotImplementedError, "derived class failed to implement
'whatSomethingsDo' method"

and then have target classes include ISomethingOrOther in their base class
lists. But Python does not do any compile-time enforcement with these
definitions. You *still* have to do runtime testing to see if the
NotImplemented exceptions get thrown.

2. Python supports multiple inheritance without the indirection of
interfaces, so you can just inherit implementation classes directly:

class Swimmer:
def swim():
pass

class Flyer:
def fly():
pass

class Duck(Swimmer,Flyer):
pass

and merrily write:

dd = Duck()
dd.fly()
dd.swim()
Sorry for the long discourse, I didn't have time to make it shorter.

HTH,
-- Paul
Jun 27 '06 #4
s9************@yahoo.com:
>In python , how to implement interface like the above?
Interfaces are lacking in Python, but an even more generic proposal is on
its way:
http://www.artima.com/weblogs/viewpo...?thread=155123

In the mean time, interfaces have already been implemented in Zope 3:
http://www.zope.org/Products/ZopeInterface

--
René Pijlman

"To find out what you can do with interfaces, see the interface interface,
IInterface in the IInterface module."
- Comment in Zope's Interface/__init__.py
Jul 3 '06 #5
Bruno Desthuilliers:
>Java interfaces are a workaround
Troll alert.
Jul 3 '06 #6
Rene Pijlman schrieb:
Bruno Desthuilliers:
>Java interfaces are a workaround

Troll alert.
No idea how you come to that conclusion - but he is actually right with
that.

Diez
Jul 4 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Robert Zurer | last post by:
I notice that Microsoft puts their interfaces and classes in the same assembly. For example System.Data contains OleDbConnection and IDbConnection etc. I have found it useful to keep my...
9
by: Gomaw Beoyr | last post by:
Two question about the "partial classes" (in the next wersion of ..NET). Question 1 ========== Will partial classes (in the next version of C#) have to be declared "partial" in ALL places. ...
30
by: Frank Rizzo | last post by:
We are having one of those religious debates at work: Interfaces vs Classes. My take is that Classes give you more flexibility. You can enforce a contract on the descendant classes by marking...
9
by: Sean Kirkpatrick | last post by:
To my eye, there doesn't seem to be a whole lot of difference between the two of them from a functional point of view. Can someone give me a good explanation of why one vs the other? Sean
19
by: dl | last post by:
I'll try to clarify the cryptic subject line. Let's say I have a base class 'GeometricObject' with a virtual method 'double distance (const GeometricObject &) const'. Among the derived classes...
6
by: Miguel Guedes | last post by:
Hello, I recently read an interview with Bjarne Stroustrup in which he says that pure abstract classes should *not* contain any data. However, I have found that at times situations are when it...
5
by: =?Utf-8?B?UmljaA==?= | last post by:
Greetings, I am actually a VB.Net guy, but I have worked somewhat with C++ and C#. I just want to ask about the relationship between Abstract Classes and Interfaces. My first question is if...
8
by: =?Utf-8?B?QmVu?= | last post by:
Hi, I have a couple of questions about the proper design of classes. I'll use a simple Customer class for my question. 1) Lets say that I have this Customer class like I said, and I want to...
4
by: Peter | last post by:
Hi I was wondering about the use of interfaces for "data classes". Actually I don't know the accepted term for these types of classes - they are simply classes which have getters and setters, to...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.