6. 静态方法

静态方法 @staticmethod

什么是静态方法

静态方法是定义在类的内部函数,此函数的作用域是类的内部。

说明

示例

class Mathematics:
    '''数学相关的类'''

    @staticmethod
    def myadd(x, y):
        return x + y

m = Mathematics()  # 创建一个数学类的对象

result = m.myadd(100, 200)
print(result)
result = Mathematics.myadd(1, 2)
print(result)

myadd(x, y) 是类 Mathematics 内的静态方法,类 Mathematics 和该类的对象都可以调用这个方法,但在方法内无法得知调用此方法的类和对象。

函数和方法总结

对象方法、类方法、静态方法、函数总结: