Home > Mobile >  static method that still works even when you don't declare it? (new to python)
static method that still works even when you don't declare it? (new to python)

Time:12-21

So, I did not know what static methods were so i searched it up and i made this

class Calculator:
    def __init__(self,num1,num2):
        self.num1 = num1
        self.num2 = num2

    @staticmethod
    def add(x,y):
        result = x   y
        return result

    def sub(x,y):
        result = x-y
        return result

Calculator.add = staticmethod(Calculator.add)

print(Calculator.add(3,4))

print(Calculator.sub(5,7))

as you can see, line 19 still works even without doing something like line 15, i just want to know how to use a static method, from what i have understood, a static method allows you to invoke it without creating an instance/variable to it. how does line 19 still works if there is (no line 15 but for line 19?)

Basically, I'm asking why the sub method works in a static context even without the staticmethod decorator?

CodePudding user response:

The decorator @staticmethod is enough, and you don't need line 15 because static method don't need an instance to call the method.

Once a method has been marked as static, it can be called via ClassName.StaticMethodName() call directly in code.

An example of a database connector:

class DBConnector:
  @staticmethod
  def connect(connection_str):
    # logic

DBConnector.connect({ip: '10.133.64.3',
                     user: 'xyz',
                     pass: 'something'})

CodePudding user response:

well @staticmethod may not work the way you think,

as you mentioned you still can call it directly without making an instance as the method still is art of the class.

however It can't be used as an instance method .

so this code will fail:

calc = Calculator(18,10)
calc.sub(10,10) #fail

static methods don't take self as parameter and that's why calling them like this fails.

A static method can be called either on the class (such as C.f()) or on an instance (such as C().f()). Moreover, they can be called as regular functions (such as f()).

  • Related