Python类静态方法

Python类静态方法教程

Python 类的静态方法的需要使用 @staticmethod 来修饰,且 Python 类的静态方法的 参数 没有任何的限制,可以没有任何参数,第一个参数也不必像 类方法实例方法 那样。

Python静态方法详解

定义

class People: money = 10000 @staticmethod def func_name(params): pass

说明

我们定义了一个 People 类,People 类有一个方法 func_name,func_name 方法是用 @staticmethod 修饰的,因此它是一个类静态方法。

类静态的参数没有任何的限制,可以没有任何参数,也可以有多个参数。

Python静态方法调用

Python 的静态方法调用方法有两种,一种是通过 “类名.方法名” 的方法来调用,另一种是通过 “对象.方法名” 的方法来调用。

静态方法调用详解

语法

People.func_name(params)

参数

参数 描述
People 类。
func_name 类方法。
params 参数。

说明

通过 “类名.方法名” 的方法,调用静态方法。

通过实例调用静态方法详解

语法

p.func_name(params)

参数

参数 描述
p 类的实例。
func_name 类方法。
params 参数。

说明

通过 “对象.方法名” 的方法,调用静态方法。

案例

类静态方法调用

通过类名访问类静态方法

print("嗨客网(www.haicoder.net)") class Student: @staticmethod def s_info(): print("call Student staticmethod") Student.s_info()

程序运行后,控制台输出如下:

33_python静态方法.png

我们创建了一个类 Student,接着,为该类添加了一个类静态方法 s_info,其中类静态方法必须使用 @staticmethod 修饰,且可以没有任何参数,最后,我们使用 “类名.类静态方法” 的形式调用类静态方法。

类静态方法调用

通过对象访问类静态方法

print("嗨客网(www.haicoder.net)") class Student: @staticmethod def s_info(): print("call Student staticmethod") stu = Student() stu.s_info()

程序运行后,控制台输出如下:

34_python静态方法.png

我们创建了一个类 Student,接着,为该类添加了一个类静态方法 s_info,最后,创建了一个 Student 类的实例 stu,并且通过 stu 来调用类静态方法。

Python类静态方法总结

Python 类的静态方法的需要使用 @staticmethod 来修饰,且 Python 类的静态方法的参数没有任何的限制,可以没有任何参数,第一个参数也不必像类方法和实例方法那样。Python 静态方法定义语法:

class People: money = 10000 @staticmethod def func_name(params): pass

Python 的静态方法调用方法有两种,一种是通过 “类名.方法名” 的方法来调用,另一种是通过 “对象.方法名” 的方法来调用。