2

I am a new python user. Thus it might be very silly. But what is the best way to run a class automatically (which has several functions inside) and return the result for a given value. for example:

class MyClass():
    def __init__(self,x):
        self.x=x
    def funct1(self):
       return (self.x)**2
       ##or any other function
    def funct2(self,y):
       return y/100.0
       ##or any other function
    def wrapper(self):
        y=self.funct1()
        z=self.funct2(y)
        ##or other combination of functions
        return z

Right now to run this, I am using:

run=MyClass(5)
run.wrapper()

But I want to run like this:

MyClass(5)

Which will return a value and can be saved inside a variable with out needing to use the wrapper function.

  • 1
    Do not use a class if you do not want to keep its instance, it seems like it's a function you want – Olivier Melançon Oct 09 '18 at 12:57
  • 1
    1. You could call `wrapper` inside `__init__` (but keep in mind that `__init__` can not return a value, so you'd still need to use an attribute to store the result). 2. I'm not sure `MyClass` even deserves to be / should be a class. – DeepSpace Oct 09 '18 at 12:57

3 Answers3

2

You can create a functor as below:

class MyClass(object):
    def __init__(self,x):
        self.x=x
    def funct1(self):
       return (self.x)**2
       ##or any other function
    def funct2(self,y):
       return y/100.0
       ##or any other function
    def __call__(self):
        y=self.funct1()
        z=self.funct2(y)
        ##or other combination of functions
        return z

The call to this functor will be like as follow:

MyClass(5)()   # Second () will call the method __call__. and first one will call constructor

Hope this will help you.

Mohit Thakur
  • 565
  • 5
  • 12
0

So when you write MyClass(5), you're instatiating a new instance of that class: MyClass and so the short answer is no, you do need the wrapper because when you instantiate the class it will necessarily return the object and not a certain value.

If you want to just return a value based on the input (say 5) consider using a function instead.

The function would be like:

   def my_func(x):
        y = x**2
        z = y/100.0
        return z

There a lots of reasons to use classes, see this answer https://stackoverflow.com/a/33072722/4443226 -- but if you're just concerned with the output of an operation/equation/function then I'd stick with functions.

Nevermore
  • 7,141
  • 5
  • 42
  • 64
-1

__init__ method should return None.
documentation link

no non-None value may be returned by init()

Yuriy Leonov
  • 536
  • 1
  • 9
  • 33