编程语言
首页 > 编程语言> > Python中的静态方法?

Python中的静态方法?

作者:互联网

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

ClassName.StaticMethod ( )

解决方法:

是的,使用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:

06002

The @staticmethod form is a function 07003 – see the description of function definitions in 07004 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 07005.

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

New in version 2.2.

Changed in version 2.4: Function decorator syntax added.

标签:python,static-methods
来源: https://codeday.me/bug/20190911/1803489.html