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
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.
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)!
精彩评论