tags:

views:

77

answers:

2

How would I get return values in this case. (as I would a function)

class A(object):
    def __init__(self,a,b):
        self.a = a
        self.b = b
        self.run()
    def run(self):
        return a + b

When I do that I get an instance, how would I get a return value?

Thanks James

+4  A: 

Are you trying to do something like:

class A(object):
    def __init__(self,a,b):
        self.a = a
        self.b = b
    def __call__(self):
        return self.a + self.b

a = A(3, 4)
a() # returns 7

It's not clear what you want and why. __init__ modifies the self object, but is required to return None (i.e. no return). Anything else will cause a TypeError.

EDIT: To avoid creating an instance, you can override __new__:

class A(object):
    def __new__(self,a,b):
        return A.run(a, b);
    @staticmethod
    def run(a, b):
        return a + b

You still haven't quite explained why you need this.

Matthew Flaschen
Yes I am trying to do exactly what your code is doing but I don't want an instance.
James
If you want a return value and not an instance, why are you trying to use a class instead of a function?
Nathan Kitchen
+1  A: 

The main purpose of calling a type is to create (and return) an instance of that type -- though you may play tricks with __new__ to work around that, why, in the name of everything that matters, would you want to code a type that's intrinsically impossible to instantiate by the normal means?! Looks like you have something "clever" in mind, but, remember, "clever" is not a compliment in the Python community... rather, Python is about simplicity. Just use a function (or any other callable, e.g. an instance of a class with a __call__ method, for advanced but still quite reasonable use cases)!

Alex Martelli
Nothing too fancy. All I want is a class function like functionality (that you can use as a function) and if needed can call or use some methods aside from the main one.
James
@user386: without an instance, the "some methods" you're calling are just functions with some extra complication but without any real benefit over perfectly normal, honest, regular functions. Just use functions and make your life simpler!
Alex Martelli