On 12/06/13 19:32, Khalid Al-Ghamdi wrote:
Hi,

Why doesn't this work? And is there way to have an
object immediately return a value or object once it is instantiated with
using a method call?

It does return a value. It returns the object that was just instantiated.

Supposed you could do what you wanted:


    1. >>> class k:
    2.         def __init__(self,n):
    3.                 return n*n
    4.
    5.
    6. >>> khalid=k(3)

and khalid receives the value 9. That would be useless, because the instance of 
class K would be immediately destroyed.

If you want to just return a value, use a function. This is the best solution:


def k(n):
    return n*n

khalid = k(3)
assert khalid == 9



Another alternative is to create a callable object:

class K:
    def __init__(self, n):
        self.n = n
    def __call__(self, arg):
        return arg * self.n

k = K(3)
k(2)
=> returns 6
k(5)
=> returns 15


A third alternative is to use the __new__ method. This only works in Python 3, 
or for new-style classes that inherit from object:

class K(object):
    def __new__(cls, n):
        return n*n


but don't do this. Really, don't. There are advanced uses where this is useful, 
but for this trivial example, you should just use a function.




--
Steven
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to