什么是Python类中的静态方法?
Python 中的静态方法与实例方法相比,不与对象绑定。换言之,静态方法无法访问或更改对象状态。此外,Python 不会自动为静态方法提供 self 或 cls 参数。因此,无法通过静态方法访问或更改类的状态。
更多Python相关文章,请阅读:Python 教程
Python中的静态方法
实际上,您可以使用静态方法在类中定义具有某些逻辑关系的实用程序方法或组函数。
这非常类似于在类内部定义常规函数来定义静态方法。
实例
使用 @staticmethod 装饰符定义静态方法 –
class name_of_class:
@staticmethod
def name_of_static_method(parameters_list):
pass
print ('static method defined')
输出
上面代码的输出如下 –
static method defined
调用静态方法
无需创建类实例即可直接从类中调用静态方法。静态方法只能访问静态变量; 无法访问实例变量。
语法
用于调用静态方法的语法如下 –
Name_of_class.static_method_name()
实例
以下是使用 Name_of_class.static_method_name() 和使用类对象调用静态方法的示例 –
class Animal:
@staticmethod
def test(a):
print('static method', a)
# 调用静态方法
Animal.test(12)
# 使用对象调用
anm = Animal()
anm.test(12)
输出
以下是上面代码的输出 –
static method 12
static method 12
实例
从另一个方法调用静态方法
我们现在将讨论从同一类的另一个静态方法中调用静态方法的过程。在这里,我们将区分静态方法和类方法:
class Animal :
@staticmethod
def first_static_method():
print('first_static_method')
@staticmethod
def second_static_method() :
Animal.first_static_method()
@classmethod
def class_method(cls) :
cls.second_static_method()
# 调用类方法
Animal.class_method()
输出
下面是上面代码的输出 –
first_static_method
使用 @staticmethod 装饰符创建静态方法
在方法定义之前加上@staticmethod装饰器以使方法静态化。Python包括一个名为@staticmethod的内置函数装饰器,可用于声明方法为静态方法。它是一个表达式,紧随我们函数定义之后评估的。
例子
静态方法是一种特殊类型的方法。有时您会编写作为类的一部分但根本不使用实际对象的代码。它是一个实用方法,可以无需对象(self参数)进行运行。由于它是静态的,所以我们以这种方式声明它。此外,我们可以从另一个类方法中调用它。
为了说明,我们来开发一个名为“information()”的静态方法,它接受一个“kingdom”并返回需要履行该王国的所有要求的列表 –
class Animal(object):
def __init__(self, name, species, kingdom):
self.name = name
self.species = species
self.kingdom = kingdom
@staticmethod
def information(kingdom):
if kingdom == 'Animalia':
info = ['lion', 'Pantheria', 'Animalia']
else:
info = ['lion']
return info
# 实例方法
def call(self):
# 从实例方法中调用静态方法
info = self.information(self.kingdom)
for i in info:
print('收集的信息', i)
anm = Animal('Lion','Pantheria', 'Animalia')
anm.call()
输出
以下是上述代码的输出 –
收集的信息 狮子
收集的信息 钱豹
收集的信息 动物界
staticmethod()函数
有些程序可以通过将staticmethod()作为函数而不是装饰器来定义旧式静态方法。
如果您需要支持Python之前的旧版本(2.2和2.3),则应仅使用staticmethod()函数定义静态方法。在所有其他情况下,建议使用@staticmethod装饰器。
语法
以下是staticmethod()函数的语法 –
staticmethod(function)
其中,
您要将其更改为静态方法的方法称为函数。它返回被转换为静态方法的方法。
例子
以下是staticmethod()函数的例子 –
class 动物:
def 测试(a):
print('静态方法', a)
# 转换为静态方法
动物.测试 = staticmethod(动物.测试)
# 调用静态方法
动物.测试(5)
输出
以下是上述代码的输出 −
静态方法 5
注意 − 当您需要一个来自类体的函数的引用但不想自动转换为实例方法时,静态方法() 的方法很有用。
极客教程