-2

Currently I am doing this to use SampleClass.method1():

output = SampleClass().method1(input_var)

But instead, I want to do this:

output = SampleClass.method1(input_var).

How do I do this?

class SampleClass(object):

    def __init__(self):
        self.var1 = 'var1'
        self.var2 = 'var2'

    def method1(self, input_var):
        self.var3 = self._method2(input_var)
        return self._method3(self.var3)

    def _method2(self):
        pass

    def _method3(self):
        pass

Is it feasible to change the above class to the following?

class SampleClass(object):

    def __init__(self, input_var):
        self.var1 = 'var1'
        self.var2 = 'var2'
        return self.method1(input_var)

    def method1(self, input_var):
        self.var3 = self._method2(input_var)
        return self._method3(self.var3)

    def _method2(self):
        pass

    def _method3(self):
        pass

Thank you.

Bo Peng
  • 561
  • 2
  • 8
  • 17
  • 2
    You can write a class method, but `method1` is accessing instance variables, so it only makes sense as an instance method. – khelwood Jul 11 '19 at 22:10
  • 1
    `method1()` uses the instance `self` in the method. What do you want that to be? – Mark Jul 11 '19 at 22:10
  • Can you give me some example code? The class structure can change, I just want to write a class that uses a method where it doesn't have to do this: SampleClass().method1(input_var) to call the method, but instead does this: SampleClass.method1(input_var). Thanks. – Bo Peng Jul 11 '19 at 22:23
  • 1
    See e.g. [Static methods in Python?](https://stackoverflow.com/questions/735975/static-methods-in-python) – khelwood Jul 12 '19 at 08:17

1 Answers1

1

What you are looking for is called a static method. And yes, you can write one in Python. A good example with explanation has been already posted here.

jsamol
  • 3,042
  • 2
  • 16
  • 27