class StaticClass:
# 静态变量
static_variable = "这是一个静态变量"
def __init__(self):
pass
@staticmethod
def static_method():
# 静态方法,不需要实例化类就可以调用
print("这是一个静态方法")
@classmethod
def class_method(cls):
# 类方法,可以通过类名或实例调用
print(f"这是一个类方法,访问类变量: {cls.static_variable}")
# 调用静态方法
StaticClass.static_method()
# 调用类方法
StaticClass.class_method()
# 访问静态变量
print(StaticClass.static_variable)
@staticmethod
装饰器定义的方法,不需要传递 self
或 cls
参数,可以直接通过类名调用。@classmethod
装饰器定义的方法,传递的是类本身(cls
),可以通过类名或实例调用,并且可以访问类变量。下一篇:python c++混合编程
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站