Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

python - Python中的静态方法?(Static methods in Python?)

Python中是否可以有无需初始化类即可调用的静态方法,例如:

ClassName.static_method()
  ask by Joan Venge translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yep, using the staticmethod decorator

(是的,使用staticmethod装饰器)

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

MyClass.the_static_method(2)  # outputs 2

Note that some code might use the old method of defining a static method, using staticmethod as a function rather than a decorator.

(请注意,某些代码可能使用定义静态方法的旧方法,将staticmethod用作函数而不是装饰器。)

This should only be used if you have to support ancient versions of Python (2.2 and 2.3)

(仅当您必须支持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

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

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

Finally, use staticmethod() sparingly!

(最后,请谨慎使用staticmethod() !)

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.

(在极少数情况下,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.

(@staticmethod形式是一个函数装饰器 –有关详细信息,请参见函数定义中的函数定义说明。)

It can be called either on the class (such as Cf() ) or on an instance (such as C().f() ).

(可以在类(例如Cf() )或实例(例如C().f() )上调用它。)

The instance is ignored except for its class.

(该实例除其类外均被忽略。)

Static methods in Python are similar to those found in Java or C++.

(Python中的静态方法类似于Java或C ++中的静态方法。)

For a more advanced concept, see classmethod() .

(有关更高级的概念,请参见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.

(2.2版中的新功能。)

Changed in version 2.4: Function decorator syntax added.

(在版本2.4中更改:添加了函数装饰器语法。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...