[Tutor] Please explain TypeError
Dave Angel
d at davea.name
Mon Aug 22 00:17:29 CEST 2011
On 08/21/2011 05:35 PM, D. Guandalino wrote:
> Python documentation says:
>
>> exception TypeError
>>
>> Raised when an operation or function is applied to an object of
>> inappropriate type. The associated value is a string giving details
>> about the type mismatch.
> For example:
>
>>>> 'foo' + (1, 2)
> Traceback (most recent call last):
> File "<stdin>", line 1, in<module>
> TypeError: cannot concatenate 'str' and 'tuple' objects
>
> So far so good. But why the following code gives a TypeError too?
>
>>>> class C(object):
> ... def __init__(self):
> ... pass
> ...
>>>> C(1)
> Traceback (most recent call last):
> File "<stdin>", line 1, in<module>
> TypeError: __init__() takes exactly 1 argument (2 given)
>
> I'm having hard times understanding why a TypeError is raised here.
> Could you explain?
>
You didn't supply a parameter in the __init__() to receive the value of
1. The self argument is automatically supplied by Python for all
ordinary method calls including initial object construction. So when
you say C(1) you're actually going to get 2 arguments in the
__init__() call.
Add another parm to the definition:
def __init__(self, startvalue):
pass
--
DaveA
More information about the Tutor
mailing list