模块"重载"
命题
Davies Liu <[email protected]> sender-time Sent at 00:42 (GMT+08:00). Current time there: 9:08 AM. ✆ reply-to [email protected] to python-cn <[email protected]> date Wed, Mar 10, 2010 at 00:42 subject [CPyUG] 一种实现模块“重载”的方法
今天因重构代码需要,发现了一种巧妙的方法实现模块级别的"重载",即重新实现模块中的若干内部函数的功能得到一个新模块。
使用方法为:
a.py
b.py
测试
>>> import a, b >>> a.foo() bar in a >>> b.foo() bar in b
=== callby.py callby callby 的实现也非常简单:
1 def clone_func(f, g):
2 "inspect a func f with globals g"
3 return f.__class__(f.func_code, g, f.func_name, f.func_defaults)
4
5 def callby(caller):
6 "auto inspect callers for a function"
7 def deco(f):
8 g = f.func_globals
9 callers = [caller,] if not isinstance(caller, (list, tuple)) else caller
10 for c in callers:
11 if c.func_globals is not g:
12 g[c.func_name] = clone_func(c, f.func_globals)
13 return f
14 return deco
破题
张沈鹏 <[email protected]> sender-time Sent at 01:40 (GMT+08:00). Current time there: 9:10 AM. ✆ reply-to [email protected] to [email protected] date Wed, Mar 10, 2010 at 01:40
这样写流程更清晰
劝题
limodou <[email protected]> sender-time Sent at 09:06 (GMT+08:00). Current time there: 9:10 AM. ✆ reply-to [email protected] to [email protected] date Wed, Mar 10, 2010 at 09:06
callby这种用法很不好理解,不直观,
- 我的建议是直接定义foo,如果它调用的bar不是a.py的,则再定主乐bar不是更好。
- 从上例来看,foo本身可能是不变的,但是它调用的bar却发生了变化。
- 但是不如重新定义foo这样更让人容易理解a.py,
- b.py之间的差异。如果要是再复杂,那还不如直接使用class呢,更清晰。
反馈
创建 by -- ZoomQuiet [2010-03-10 01:11:50]