登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

Code@Pig Home

喜欢背着一袋Code傻笑的Pig .. 忧美.欢笑.记忆.忘却 .之. 角落

 
 
 

日志

 
 

[Python] Class-Level Method 以及 Decorator 的一点点

2006-10-10 21:53:33|  分类: lang_python |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
Python 中的 class ,除了拥有 def foobar(self, ...) 这种格式的函数外,还可以拥有类似 C++ 的静态函数。Python 中又可将其分为两类:

1. static method
2. class method

两者的用法如下:
# -- static method --
class foobar(object):
def foo():
print "static"
foo = staticmethod(foo)

f = foobar()
f.foo()

foobar.foo()

# ---

# -- class method --
class foobar(object):
def foo(cls):
print "class", cls
foo = classmethod(foo)

f = foobar()
f.foo()

foobar.foo()
可以认为,static method 就是我们平常的静态函数。而 class method 会自动帮你传入一个当前 class 类型,类似 instance 自动帮你传一个 self 查不多。

但这样的写法很麻烦,不是吗?因此,可以利用 Python 中的 Decorator 来简化这种写法。Decorator 的具体定义,可以参见 PEP 318,我也没细看,理解不多。而这里也有一篇不错的文字《Decorators in Python》,介绍了 Decorator 在 Python 中的用法。我这里仅仅使用其最基本的用法——简化 class level method 的代码。

下面是具体的例子,和上面写法的效果是一样的。
# -- static method -- 
class foobar(object):
@staticmethod
def foo():
print "static"

----
PS: 今日读了几章 Python in Nutshell,浮光掠影地学到了 new-style class、descriptor、decorator 等名词,Python 的倩影,在我眼中模糊起来。语言真的是复杂了就好么?疑惑 ...

  评论这张
 
阅读(2045)| 评论(2)

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2018