Python 静态方法

Python 静态方法

In this quick post, we will learn how to create and use a Python static method. We will also have a look at what advantages and disadvantages static methods offer as compared to the instance methods. Let's get started. python static method

什么是静态方法?

Python 中的静态方法与 python 类级别方法非常相似,不同之处在于静态方法与一个类而不是该类的对象有关,这意味着静态方法可以被称为没有该类的对象,这也意味着静态方法不能改变对象的状态,因为它们不与它有关。

创建 Python 静态方法

Python 静态方法可以以两种方式创建,让我们来看看这里的每个方法:

使用静态方法( )

让我们直接跳到样本代码片段,了解如何使用staticmethod()方法:

1class Calculator:
2
3    def addNumbers(x, y):
4        return x + y
5
6# create addNumbers static method
7Calculator.addNumbers = staticmethod(Calculator.addNumbers)
8
9print('Product:', Calculator.addNumbers(15, 110))

Note that we called the addNumbers we created without an object. When we run this program, here is the output we will get: python staticmethod function There were no surprises there. This approach is controlled as at each place, it is possible to create a static method out of a class method as well. Let's see another approach with the same example here.

使用 @staticmethod

这是创建一个静态方法的一种更微妙的方式,因为我们不必依赖于一种方法是类方法的陈述定义,并在每个地方使其静态。

1class Calculator:
2
3    # create addNumbers static method
4    @staticmethod
5    def addNumbers(x, y):
6        return x + y
7
8print('Product:', Calculator.addNumbers(15, 110))

When we run this program, here is the output we will get: python static method annotation This was actually a much better way to create a static method as the intention of keeping the method static is clear as soon as we create it and mark it with the @staticmethod annotation.

Python 静态方法的优点

静态方法有一个非常明确的用例,当我们需要一些功能,而不是一个对象,而不是一个完整的类,我们使一个方法静态。当我们需要创建实用方法时,这是相当有益的,因为它们通常不关联到一个对象生命周期。

Published At
Categories with 技术
Tagged with
comments powered by Disqus