gpt4 book ai didi

python - Python中的静态方法?

转载 作者:bug小助手 更新时间:2023-10-28 01:27:59 25 4
gpt4 key购买 nike

我可以定义一个 static method我可以直接在类实例上调用哪个?例如,

MyClass.the_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)时才应使用此选项:

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),只是没有使用漂亮的装饰器语法。

最后,使用 staticmethod节俭!在 Python 中很少有需要静态方法的情况,我已经看到它们被多次使用,单独的“顶级”函数会更清晰。


The following is verbatim from the documentation: :

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, ...): ...

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

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.

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.

New in version 2.2.

Changed in version 2.4: Function decorator syntax added.

关于python - Python中的静态方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/735975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com