静态方法装饰器
本课属于 Coddy Python 学习旅程的“面向对象编程”单元。第 11 课,共 64 课。
@staticmethod 装饰器可以创建不需要 self 或类的方法。它们的工作方式和普通函数一样,但属于类。
下面是一个包含静态方法的类示例:
class MathHelper:
@staticmethod
def add(a, b):
return a + b
@staticmethod
def is_even(number):
return number % 2 == 0使用类名调用静态方法:
result = MathHelper.add(5, 3)
print(result)
check = MathHelper.is_even(10)
print(check)你也可以从对象中调用它们:
helper = MathHelper()
result2 = helper.add(2, 4)
print(result2)输出:
8
True
6静态方法无法访问实例数据或类数据:
class Calculator:
brand = "Python Calc"
def __init__(self, owner):
self.owner = owner
@staticmethod
def multiply(x, y):
# 无法访问 self.owner 或 Calculator.brand
return x * y要点:当你需要一个与类相关、但不需要访问实例(self)或类数据的函数时,请使用 @staticmethod。不需要 self 参数。
亲手试试
这节课没有代码挑战。
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向对象编程中的所有课
自己练习: Python 在线编译器