Date manipulation and Java 'interface' equivalents

Peter Hansen peter at engcorp.com
Sun Nov 5 23:13:54 CET 2000


Martin Christensen wrote:
> 
> First of all, I am doing some statistics with a PostgreSQL database,
> and for this I need to manipulate some dates, ie. add a week to this
> date or subtract a month from another. 

http://starship.python.net/crew/lemburg/mxExtensions.html#mxDateTime

> Second question: is there a Python equivalent of Java interfaces? In a
> matter of months I'll be constructing a web based sales and customer
> relations thingy, and a similar feature would really make things
> easier. I haven't decided on the implementation language yet, but
> this is one of the things that make Java more appealing.

Assuming you absolutely want the safety restrictions that an interface
gives you (as opposed to the freer style of programming Python gives
you, which might be more appropriate for writing a "thingy"), how about
something like the following?  (I don't know whether this would "really
make things easier", though.  And you still miss what is perhaps the
only benefit of the Java interface: compile-time error messages.)

>>> class AnInterface:
...     someConstant = 5
...     def someMethod(self):
...         raise NotImplementedError
...
>>> class BadInterface(AnInterface):
...     pass
...
>>> class GoodInterface(AnInterface):
...     def someMethod(self):
...         print 'someConstant is %s' % AnInterface.someConstant
...
>>> x = GoodInterface()
>>> x.someMethod()
someConstant is 5
>>> y = BadInterface()
>>> y.someMethod()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 4, in someMethod
NotImplementedError
>>>

-- 
Peter Hansen



More information about the Python-list mailing list