##language:zh #pragma section-numbers off ##含有章节索引导航的 ZPyUG 文章通用模板 <> ## 默许导航,请保留 <> = 模块"重载" = ##startInc == 命题 == {{{ Davies Liu sender-time Sent at 00:42 (GMT+08:00). Current time there: 9:08 AM. ✆ reply-to python-cn@googlegroups.com to python-cn date Wed, Mar 10, 2010 at 00:42 subject [CPyUG] 一种实现模块“重载”的方法 }}} 今天因重构代码需要,发现了一种巧妙的方法实现模块级别的"重载",即重新实现模块中的若干内部函数的功能得到一个新模块。 使用方法为: === a.py === {{{#!python def bar(): return 'bar in a' def foo(): print bar() }}} === b.py === {{{#!python from a import * from luzong.utils import callby @callby(foo) def bar(): return 'bar in b' }}} === 测试 === {{{ >>> import a, b >>> a.foo() bar in a >>> b.foo() bar in b }}} === callby.py callby callby 的实现也非常简单: {{{#!python def clone_func(f, g): "inspect a func f with globals g" return f.__class__(f.func_code, g, f.func_name, f.func_defaults) def callby(caller): "auto inspect callers for a function" def deco(f): g = f.func_globals callers = [caller,] if not isinstance(caller, (list, tuple)) else caller for c in callers: if c.func_globals is not g: g[c.func_name] = clone_func(c, f.func_globals) return f return deco }}} == 破题 == {{{ 张沈鹏 sender-time Sent at 01:40 (GMT+08:00). Current time there: 9:10 AM. ✆ reply-to python-cn@googlegroups.com to python-cn@googlegroups.com date Wed, Mar 10, 2010 at 01:40 }}} 这样写流程更清晰 {{{#!python import a import sys sys.modules['xxxx']=sys.modules['a'] del sys.modules['a'] import a import xxxx from xxxx import * xxxx.bar = lambda:"b" a.foo() foo() }}} == 劝题 == {{{ limodou sender-time Sent at 09:06 (GMT+08:00). Current time there: 9:10 AM. ✆ reply-to python-cn@googlegroups.com to python-cn@googlegroups.com date Wed, Mar 10, 2010 at 09:06 }}} callby这种用法很不好理解,不直观, * 我的建议是直接定义foo,如果它调用的bar不是a.py的,则再定主乐bar不是更好。 * 从上例来看,foo本身可能是不变的,但是它调用的bar却发生了变化。 * 但是不如重新定义foo这样更让人容易理解a.py, * b.py之间的差异。如果要是再复杂,那还不如直接使用class呢,更清晰。 ##endInc ---- '''反馈''' 创建 by -- ZoomQuiet [<>]