- 论坛徽章:
- 2
|
本帖最后由 OwnWaterloo 于 2011-04-07 09:06 编辑
有一些函数可以接受函数为参数, 并返回新的函数。
比如 staticmethod。
- def X :
- def f(*rest) : print rest
- def g(*rest) : print rest
- g = staticmethod(g)
复制代码 x = X() # <__main__.X instance at ...>
x.f() # (<__main__.X instance at ...>, )
x.f(12) # (<__main__.X instance at ...>, 12)
没有经过staticmethod修饰的函数f, 会将 instance 作为一个隐式参数传递, 作为 f 的第1个参数。
x.g() # ()
x.g(12) # (12,)
而经过 staticmethod 修饰的函数g, 就不会传入这个隐式参数。
考虑这样一种情况:
- class Y :
- def f(*rest) :
- # very long
- f = staticmethod(f)
复制代码 大致有这样一些弊端:
1. f的名字被重复了3次, 违反DRY
2. 如果f的定义很长, 容易漏掉 "f被修饰过" 的信息
而 decorator 的语法:
- class Y :
- @staticmethod
- def f(*rest) :
- # very long
复制代码 就可以避免上那些问题。 |
|