约 621 字
约 3 分钟
说明:把一个方法封装成类方法。参考 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()
Loading...
创建于 2025/5/9 23:27:43
更新于 2025/5/11 16:48:17