overloading on type?
Steve Purcell
stephen_purcell at yahoo.com
Wed Feb 14 06:47:10 EST 2001
Burkhard Kloss wrote:
> in python, I catch myself writing things along the lines of
>
> class date:
> def __init__ (self, arg):
> if type(arg) == types.InstanceType:
> ....
> elif type(arg) == types.IntType:
> ...
>
> which works, but just seems so *wrong*.
There are cases where this sort of type check is the best way to make a
clear API. A solution might be:
class Date:
def __init__(self, millis): # construct with int or long
self.millis = millis
def parse_date(str):
millis = ...
return Date(millis)
This is quite common in the standard libraries. There are many module-level
functions that 'return an object of type ...', and the mechanism for
constructing such objects directly is deliberately obscured.
Modules form a convenient namespace for factory methods.
-Steve
--
Steve Purcell, Pythangelist
http://pyunit.sourceforge.net/
http://pyserv.sourceforge.net/
Available for consulting and training.
"Even snakes are afraid of snakes." -- Steven Wright
More information about the Python-list
mailing list