Static methods in Python?

后端 未结 10 926
悲&欢浪女
悲&欢浪女 2020-11-22 02:36

Is it possible to have static methods in Python which I could call without initializing a class, like:

ClassName.static_method()
10条回答
  •  没有蜡笔的小新
    2020-11-22 02:53

    Python Static methods can be created in two ways.

    1. Using staticmethod()

      class Arithmetic:
          def add(x, y):
              return x + y
      # create add static method
      Arithmetic.add = staticmethod(Arithmetic.add)
      
      print('Result:', Arithmetic.add(15, 10))
      

    Output:

    Result: 25

    1. Using @staticmethod

      class Arithmetic:
      
      # create add static method
      @staticmethod
      def add(x, y):
          return x + y
      
      print('Result:', Arithmetic.add(15, 10))
      

    Output:

    Result: 25

提交回复
热议问题