Date manipulation and Java 'interface' equivalents

Alex Martelli aleaxit at yahoo.com
Tue Nov 7 18:46:39 EST 2000


"Martin Christensen" <knightsofspamalot-factotum at mail1.stofanet.dk> wrote in
message news:87n1fbqzu8.fsf at fangorn.stofanet.dk...
    [snip]
> I'm not sure I get your point, and I'd much appreciate elaboration. I

Why, sure!

> have to manipulate different goods, say, knobs, dials and
> blinkenlights, and each of these are represented by objects of
> different classes, naturally.

OK.

> However, for some operations I want to
> manipulate these objects without necessarily knowing what kind of
> objects they are.

Yes: polymorphism.

> In Java I would accomplish this by having them
> implement an interfacy Thingy that enables me to throw them around as
> I wish, and when I need the specific qualities of a certain class I
> can cast the Thingy object to whatever's relevant.

In Python, you accomplish this in a simpler way:
a. have your objects define the methods you desire to
    call (whether by inheriting them, or directly);
b. have your client-code calls said methods on the objects.

There is no need to 'group' methods up into 'interfaces' in
a formal way, to implement 'the interface' (just the methods)
in the objects, nor to cast in the client-code (just call the
methods you need directly on the object).

Just as you would use a try/except block around the cast
in Java (if it can possibly fail), so may you use such a
block in Python around the method-calls (if they can
possibly fail, be it because a certain object doesn't have
the method [you'll get an AttributeError exception], or
any other reason [other exceptions]).


> Alex> The formalization of the 'interface' concept in Java does not
> Alex> really buy you all that much in practice compared with Python's
> Alex> pragmatically-equivalent (more dynamic and fluid) approach.
>
> I wouldn't know, since I'm a newcomer to Python and dynamic typing in
> general.

Ok.  But I'm sure you can see that, if interface X comprises
methods A, B, C, then Java's "implements X" just means an
object defines each of these methods (with suitable
signature); in Python, you simply define each of them, and
that's it.  (The static, compile-time typing checks are not
feasible in Python, of course; that, if cost it be, is the cost
of dynamic typing -- the diagnosis is by runtime raising of
exceptions, good unit-testing is needed [not that you can
do without it in static-typing languages...]).


Alex






More information about the Python-list mailing list