621

3 分钟

#classmethod

说明:把一个方法封装成类方法。参考 staticmethod 函数。

def classmethod(fn): ''' 把一个方法封装成类方法 :param fn: 要封装的方法 :return: 封装后的方法 '''

类方法隐含的第一个参数就是类,就像实例方法接收实例作为参数一样。 要声明一个类方法,按惯例请使用以下方案:

class C: @classmethod def fn(cls, arg1, arg2): pass

示例:

class Cat: @classmethod def speak(cls): print('喵喵喵') # 通过类调用 Cat.speak() # 通过对象调用 cat = Cat() cat.speak()

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

创建于 2025/5/9

更新于 2025/5/11