Python 类中的静态方法是什么?
与实例方法相比,Python 中的静态方法不绑定到对象。换句话说,对象状态不能通过静态方法访问或更改。此外,Python 不会自动将 self 或 cls 参数提供给静态方法。因此,类的状态不能通过静态方法访问或更改。
Python 中的静态方法
实际上,您可以使用静态方法在类中定义具有某些逻辑关系的实用方法或组函数。
在类中定义静态方法与定义常规函数非常相似。
示例
The @staticmethod decorator is used to define static methods −
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) # calling a static method Animal.test(12) # calling using object 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() # calling the class 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 # the instance method def call(self): # calling the static method from the instance method info = self.information(self.kingdom) for i in info: print('Information collected', i) anm = Animal('Lion','Pantheria', 'Animalia') anm.call()
输出
以下是上述代码的输出 -
Information collected lion Information collected Pantheria Information collected Animalia
staticmethod() 函数
某些程序可能以老式的方式定义静态方法,即通过将 staticmethod() 调用为函数而不是装饰器。
如果您需要支持以前的 Python 版本(2.2 和 2.3),则应仅使用 staticmethod() 函数定义静态方法。在所有其他情况下,建议使用 @staticmethod 装饰器。
语法
以下是 staticmethod() 函数的语法 -
staticmethod(function)
其中,
您想要更改为静态方法的方法称为函数。它返回转换后的静态方法。
示例
以下是 staticmethod() 函数的示例 −
class Animal: def test(a): print('static method', a) # converting to the static method Animal.test = staticmethod(Animal.test) # calling the static method Animal.test(5)
输出
以下是上述代码的输出 -
static method 5
注意 - 当您需要从类主体中引用函数但又不希望自动转换为实例方法时,staticmethod() 方法会很有用。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

