473,809 Members | 2,797 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1824
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.goo glegroups.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.r r._bogus_.com> wrote in message
news:ZO******** **********@torn ado.texas.rr.co m...

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 passBackSomethi ngImportant() {
// 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 ISomethingOrOth er:
def whatSomethingsD o(blah, blah2):
raise NotImplementedE rror, "derived class failed to implement
'whatSomethings Do' method"

and then have target classes include ISomethingOrOth er 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,Fl yer):
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
1514
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 interfaces in a separate assembly for a number of reasons. Among them are Avoiding circular references Hiding implementation from a remoting client Supporting polymorphic behavior across classes
9
2536
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. I.e. do we have to need to write:
30
2518
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 methods abstract (which is all that an interface does). In addition, the classes allow you to be flexible by adding functionality that child classes inherit. Or by providing optional functionality via virtual methods. Now, I understand that...
9
5202
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
1838
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 I have eg 'Segment', representing a segment of a line, and 'Arc', representing an arc of circle. What is the right place to put the code for computing the distance between a Segment and an Arc? It is not specific to the Segment nor to
6
4036
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 would be useful to have /some/ data defined in such an abstract class for reasons of forming a common block of data existing in or used by all descendant classes (see example below.) In such a case where a common block of data *always* exists,...
5
3019
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 C# even has Iinterfaces. I took some Java programming classes and Interfaces are a main staple of Java. And in VB.Net I use interfaces for setting up definitions of classes. I am guessing that Abstract classes in C# do the same thing as...
8
1636
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 distinguish between different types of customers, for example private, business, other etc. This will allow me to filter customers based on their type. Should I
4
1388
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 contain data and not really provide any functions. Is it worth defining interfaces for these types of classes, or is it "overkill"?
0
9721
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9602
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10639
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10376
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10120
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7661
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3861
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3015
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.