Overloading __init__ & Function overloading
John J. Lee
jjl at pobox.com
Fri Sep 30 16:01:27 EDT 2005
Paul Rubin <"http://phr.cx"@NOSPAM.invalid> writes:
> "Iyer, Prasad C" <prasad.c.iyer at capgemini.com> writes:
> > But I want to do something like this
> >
> > class BaseClass:
> > def __init__(self):
> > # Some code over here
> > def __init__(self, a, b):
> > # Some code over here
> > def __init__(self, a, b, c):
> > # some code here
>
> You can only use one __init__ method. You'd have it count the args:
>
> class BaseClass:
> def __init__(self, *args):
> if len(args) == 2:
> a, b = args
> # some code
> elif len(args) == 3:
> a, b, c = args
> # more code
Weeellll... more readably, you can use:
1. Named arguments (aka "keywords arguments" -- though a keyword arg
isn't a keyword, of course...)
2. Factory (class methods) (I'm using those parentheses around "class
methods" for precedence, not annotation -- unlike here ;-)
3. Plain old factory methods
4. Factory "functions" implemented as classes with a __call__ method
5. Factory classes with named factory methods (perhaps even class
methods)
6. Plain old factory functions
It's all terribly restrictive, as you can see <wink>
(Yes, I know the OP used the same name to call all the constructors in
his examples -- but that's just an expectation carried over from other
languages)
John
More information about the Python-list
mailing list