constructor overloading like Java ?
Gerhard Häring
gh at ghaering.de
Mon May 26 10:10:56 EDT 2003
Servus Karl :-)
Karl Scalet wrote:
> Hello Markus,
>
> Markus Jais wrote:
>>[...] public MyClass(int a)
>> public MyClass(MyObject my)
> [...]
>
> you cannot have more than one contructor, but you could handle
> this case inside _the_ constuctor:
>
> class MyClass:
> def __init__(arg):
> if type(arg) == type(0):
> self.a = arg
> elif isinstance(arg, MyObject):
> self.my = arg
>
> in the latter case, arg is a MyObject or a
> subclass of it (as with Java)
<nitpick>
For checking against ints, I'd recommend you use either:
#v+
if type(arg) is int
or
if isinstance(arg, int)
#v-
Using Python 2.2 or later, of course.
The type(0) (or types.IntType) is only necessary for backwards
compatiblity with older Python versions.
Anyway, types (and any singletons) should be compared using the 'is'
operator, because it's clearer and faster.
-- Gerhard
More information about the Python-list
mailing list