在线编译器
https://c.runoob.com/compile/6

Python classmethod 修饰符

描述

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

语法

classmethod 语法:
classmethod

参数

  • 无。

    返回值

    返回函数的类方法。

    实例

    以下实例展示了 classmethod 的使用方法: ```

    !/usr/bin/python

    -- coding: UTF-8 --

class A(object): bar = 1 def func1(self):
print (‘foo’) @classmethod def func2(cls): print (‘func2’) print (cls.bar) cls().func1() # 调用 foo 方法

A.func2() # 不需要实例化

  1. 输出结果为:<br />func2<br />1<br />foo
  2. <a name="unRhc"></a>
  3. # Python staticmethod() 函数
  4. [Python 内置函数](https://www.runoob.com/python/python-built-in-functions.html)<br />python staticmethod 返回函数的静态方法。<br />该方法不强制要求传递参数,如下声明一个静态方法:<br />class C(object):<br /> @staticmethod<br /> def f(arg1, arg2, ...):<br /> ...<br />以上实例声明了静态方法**f**,从而可以实现实例化使用**C().f()**,当然也可以不实例化调用该方法**C.f()**。
  5. <a name="tq01v"></a>
  6. ### 函数语法
  7. staticmethod(function)<br />参数说明:
  8. -
  9. <a name="xv5pH"></a>
  10. ### 实例

!/usr/bin/python

-- coding: UTF-8 --

class C(object): @staticmethod def f(): print(‘runoob’);

C.f(); # 静态方法无需实例化 cobj = C() cobj.f() # 也可以实例化后调用 ``` 以上实例输出结果为:
runoob
runoob