Skip to content

Latest commit

 

History

History
33 lines (20 loc) · 1.16 KB

File metadata and controls

33 lines (20 loc) · 1.16 KB

#Python中的静态方法?

原问题地址:http://stackoverflow.com/questions/735975/static-methods-in-python

##问题:

在Python中有没有可能调用静态方法而无需对类进行初始化,如:

ClassName.StaticMethod ( )

##回答:

是的,使用staticmethod装饰器

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

MyClass.the_static_method(2) # outputs 2

请注意,某些代码可能使用老方法来定义静态法,把静态法作为函数而不是装饰器来应用。如果你不得不支持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中只有极少数情况下才有必要使用静态方法。我见过对于staticmethod()的多次使用,而这些时候,独特的“顶级”函数往往表达得更清晰。