python小菜 2009-04-09 21:23 采纳率: 0%
浏览 739
已采纳

Python 中的静态方法?

Is it possible to have static methods in Python so I can call them without initializing a class, like:

ClassName.StaticMethod ( )

转载于:https://stackoverflow.com/questions/735975/static-methods-in-python

  • 写回答

9条回答 默认 最新

  • 关注

    Yep, using the staticmethod decorator

    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. 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
    

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

    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.


    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(8条)

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决