浙江省高等学校教师教育理论培训

微信搜索“毛凌志岗前心得”小程序

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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,差不多就是这个样子了。

posted on 2010-09-18 13:18  lexus  阅读(1235)  评论(0)    收藏  举报