python classmethod 修饰符

  • 描述:classmethod修饰符对应的函数不需要实例化,不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等。

  • 返回值:返回函数的类的方法。

  • 示例代码:

    • 1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17

      # -*- coding: UTF-8 -*-

      class (object):
      bar = 1
      def func1(self):
      print ('foo')

      def func2(cls):
      print ('func2')
      print (cls.bar)
      cls().func1() # 调用 foo 方法

      >>>A.func2() # 不需要实例化
      func2
      1
      foo
  • 参考链接:http://www.runoob.com/python/python-func-classmethod.html