金源在线客服

在线咨询

QQ在线咨询

QQ咨询

01Jan

Python中静态方法的实现

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.

上一篇:Python链表类型对象所含有的方法
下一篇:Python中使用MySQLdb插入数据中文问题