zoukankan      html  css  js  c++  java
  • Python中静态方法的实现

    Python似乎很讨厌修饰符,没有常见的static语法。其静态方法的实现大致有以下两种方法:

    第一种方式(staticmethod):

    >>> class Foo:
            str = "I'm a static method."

            def bar():
                print Foo.str

            bar = staticmethod(bar)


    >>> Foo.bar()
    I'm a static method.


    第二种方式(classmethod):

    >>> class Foo:
            str = "I'm a static method."

            def bar(cls):
                print cls.str

            bar = classmethod(bar)


    >>> Foo.bar()
    I'm a static method.


    ---------------------------------------------------------------

    上面的代码我们还可以写的更简便些:

    >>> class Foo:
            str = "I'm a static method."

            @staticmethod
            def bar():
                print Foo.str


    >>> Foo.bar()
    I'm a static method.


    或者

    >>> class Foo:
            str = "I'm a static method."

            @classmethod
            def bar(cls):
                print cls.str


    >>> Foo.bar()
    I'm a static method.


    OK,差不多就是这个样子了。

  • 相关阅读:
    你可见过一种基于状压的二进制筛法?
    dp
    tricks
    csp2020 游记
    洛谷P2982 [USACO10FEB]慢下来Slowing down
    NOIP 2018 大翻车记
    2019 ICPC 南京网络赛
    POJ2778 AC自动机 + 快速矩阵幂
    2019 CCPC网络赛
    2018ICPC 北京
  • 原文地址:https://www.cnblogs.com/lexus/p/1830145.html
Copyright © 2011-2022 走看看