[Tutor] Using __init__ to return a value

Peter Otten __peter__ at web.de
Wed Jun 12 12:03:35 CEST 2013


Khalid Al-Ghamdi wrote:

>    1. >>> class k:
>    2.         def __init__(self,n):
>    3.                 return n*n
>    4.
>    5.
>    6. >>> khalid=k(3)
>    7. Traceback (most recent call last):
>    8.   File "<pyshell#58>", line 1, in <module>
>    9.     khalid=k(3)
>    10. TypeError: __init__() should return None, not 'int'

> Why doesn't this work? 

Leaving out the details, for a class A

a = A(...)

is essentially a shortcut for

a = A.__new__(A, ...)
a.__init__(...)

__new__(), not __init__() determines what value is bound to the name a.

> And is there way to have an
> object immediately return a value or object once it is instantiated with
> using a method call?

You can write your own implementation of __new__(), but that is expert area 
and hardly ever needed. When you aren't interested in the class instance you 
shouldn't create one in the first place, and use a function instead:

def k(n):
    return n*n
khalid = k(3)



More information about the Tutor mailing list