Python似乎很討厭修飾符,沒(méi)有常見(jiàn)的static語(yǔ)法。其靜態(tài)方法的實(shí)現(xiàn)大致有以下兩種方法:
第一種方式(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.
---------------------------------------------------------------
上面的代碼我們還可以寫(xiě)的更簡(jiǎn)便些:
>>> 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,差不多就是這個(gè)樣子了。
posted on 2008-11-22 10:37
周銳 閱讀(410)
評(píng)論(0) 編輯 收藏 所屬分類(lèi):
Python