Python中的静态方法? [英] Static methods in Python?

查看:69
本文介绍了Python中的静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 Python 中有静态方法,我可以在不初始化类的情况下调用它,例如:

Is it possible to have static methods in Python which I could call without initializing a class, like:

ClassName.static_method()

推荐答案

是的,使用 staticmethod 装饰器

class MyClass(object):
    @staticmethod
    def the_static_method(x):
        print(x)

MyClass.the_static_method(2)  # outputs 2

请注意,某些代码可能会使用定义静态方法的旧方法,将 staticmethod 用作函数而不是装饰器.仅当您必须支持旧版本的 Python(2.2 和 2.3)时才应使用此方法

Note that some code might use the old method of defining a static method, using staticmethod as a function rather than a decorator. This should only be used if you have to support ancient versions of Python (2.2 and 2.3)

class MyClass(object):
    def the_static_method(x):
        print(x)
    the_static_method = staticmethod(the_static_method)

MyClass.the_static_method(2)  # outputs 2

这与第一个示例完全相同(使用 @staticmethod),只是没有使用漂亮的装饰器语法

This is entirely identical to the first example (using @staticmethod), just not using the nice decorator syntax

最后,使用 staticmethod 谨慎!在 Python 中需要静态方法的情况很少,而且我已经看到它们在单独的顶级"中使用了很多次.功能会更清楚.

Finally, use staticmethod sparingly! There are very few situations where static-methods are necessary in Python, and I've seen them used many times where a separate "top-level" function would have been clearer.

以下是文档中的逐字逐句::

静态方法不接收隐式第一个参数.要声明静态方法,请使用以下习惯用法:

A static method does not receive an implicit first argument. To declare a static method, use this idiom:

class C:
    @staticmethod
    def f(arg1, arg2, ...): ...

@staticmethod 形式是一个函数 decorator – 参见 函数定义了解详情.

The @staticmethod form is a function decorator – see the description of function definitions in Function definitions for details.

它可以在类(如C.f())或实例(如C().f())上调用.除了它的类之外,该实例被忽略.

It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class.

Python 中的静态方法类似于 Java 或 C++ 中的静态方法.有关更高级的概念,请参阅 classmethod().

Static methods in Python are similar to those found in Java or C++. For a more advanced concept, see classmethod().

有关静态方法的更多信息,请参阅 标准类型层次结构.

For more information on static methods, consult the documentation on the standard type hierarchy in The standard type hierarchy.

2.2 版中的新功能.

New in version 2.2.

在 2.4 版更改:添加了函数装饰器语法.

Changed in version 2.4: Function decorator syntax added.

这篇关于Python中的静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆