[Tutor] _init_() arguments

Christian Witts cwitts at compuscan.co.za
Fri Sep 9 12:26:30 CEST 2011


On 2011/09/09 12:10 PM, Stu Rocksan wrote:
> I have a very basic question that I am sure has a simple answer.  I
> would be very appreciative of anyone that would set me straight.
>
> Python 2.7.2
>
> I am simply trying to pass arguments.  Based on the documentation that
> I've read so far _init_() is called upon instance creation and the
> arguments are those passed to the class constructor expression.  That
> all makes sense to me but the problem is when I try to actually pass
> the argument.  I get an TypeError that states "This constructor takes
> no arguments."
>
> Even using code direct from the tutorials included in the
> documentation gives me the same error.  I doubt that there would be
> bad code coming direct from the official website...right?  So the
> problem must be me.
>
> Example:
>
> class Complex:
>                def _init_(self, realpart, imagpart)
>                      self.r = realpart
>                      self.i = imagpart
>
> x = Complex(3.0, -4.5)
> x.r, x.i
> # theoretical output
> (3.0, -4.5)
>
> This is taken direct from the tutorial included in the documentation
> dated September 8, 2011.  If you try to run this you will get a
> TypeError: this constructor takes no arguments.
>
> It even says in the explanation before this code:
> Of course, the __init__() method may have arguments for greater
> flexibility. In that case, arguments given to the class instantiation
> operator are passed on to __init__().
>
> I've tried similar code from other beginner Python books and I get the
> exact same result.
>
> I am sure that I am missing something simple.  Thanks in advance
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

__init__() has 2 underscores pre- and post-fixed.  Your example will 
break because of that, and also you're missing a colon at the end of 
your `def` line.

Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit 
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> class Complex:
...   def __init__(self, realpart, imagpart):
...     self.r = realpart
...     self.i = imagpart
...
 >>> x = Complex(3.0, -4.5)
 >>> x.r, x.i
(3.0, -4.5)
 >>> class Complex2:
...   def _init_(self, realpart, imagpart):
...     self.r = realpart
...     self.i = imagpart
...
 >>> x= Complex2(3.0, -4.5)
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: this constructor takes no arguments

-- 

Christian Witts
Python Developer

//
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110909/5078a449/attachment.html>


More information about the Tutor mailing list