Python class __init__(mandatory arguments?)
Ray Smith
ray at rays-web.com
Sun Jun 15 22:09:38 EDT 2003
Lee John Moore <leej at dsl.pipex.com> wrote in message news:<bcitu2$jrrv8$1 at ID-129053.news.dfncis.de>...
> Just for confirmation really: When I create a custom class, is
> it *really* true that def __init__() arguments can only ever be
> optional? Eg:
No, not that I know of.
> class MyClass:
> param1 = None
> param2 = None
> def __init__(self, param1, param2):
> param1 = self.param1
> param2 = self.param2
>
> myinstance1 = MyClass()
> myinstance2 = MyClass("Hello", "World")
the case of:
myinstance1 = MyClass()
should fail as far as I know.
I think what you want is something like:
class MyClass:
def __init__(self, param1=None, param2=None):
self.param1 = param1
self.param2 = param2
myinstance1 = MyClass()
myinstance2 = MyClass("Hello", "World")
Also note you had the use of self backwards in your __init__() method.
>
> I'm really unhappy that myinstance1 is allowed. ;-)
As I said I didn't think it was.
> I'm so accustomed to constructor arguments being mandatory in
> C++ & OP classes....and yes, yes, I realise __init__() is not a
> constructor (even though it looks like one), but if there's a
> way I can *force* arguments upon class instantiation, I'd like
> to know about it. :-)
Just try playing around in Python with what you have said and see
what happens.
Regards,
Ray Smith
More information about the Python-list
mailing list