class MyClass:
# 静态方法
@staticmethod
def static_method():
print("这是静态方法")
# 静态方法不能直接访问类属性或实例属性,也不能修改类的状态
# 类方法
@classmethod
def class_method(cls):
print("这是类方法")
# 类方法可以通过 cls 参数访问和修改类的状态
# 调用静态方法
MyClass.static_method()
# 调用类方法
MyClass.class_method()
静态方法 (@staticmethod
):
self
或 cls
)。类方法 (@classmethod
):
cls
,可以访问和修改类的状态。通过以上代码示例,你可以看到如何定义和使用静态方法和类方法,并理解它们的区别。
上一篇:python numba
下一篇:python 获取参数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站