Skip to main content
 首页 » 编程设计

python之函数装饰器指定 def 的前两行

2025年05月04日7zhoujg

我在 python 3.5 上:

我的一些 python 函数中有一个重复模式。对于大量的类,前两行是:

obj_a = <..... obtain something I need.....> 
obj_b = <..... obtain another thing I need....> 

我在这里简化了它,但是获取 obj_a 和 obj_b 的过程不是一个单一的类轮......我想避免在任何地方重复这段代码以比 util 函数更优雅的方式获取 obj_a 和 obj_b(例如 obj_a = getObjectA()...)

有什么方法可以把这些行放在函数的装饰器中,我有这样的东西:

@function_where_I_need_my_objects 
def foo: 
  <....do something with obj_a and obj_b already initialized....> 

请您参考如下方法:

obj_a 和 obj_b 听起来很像状态。

class Thing: 
    def __init__(self): 
        # These could also be class attributes instead 
        # if they can be initialized when Thing is first 
        # defined. 
        self.obj_a = ... 
        self.obj_b = ... 
 
    def foo(self): 
        # use self.obj_a and self.obj_b 
 
t = Thing() 
t.foo() 

定义一个返回围绕 obj_a 和 obj_b 的闭包的装饰器也是可能的。

def decorator(f): 
    obj_a = ... 
    obj_b = ... 
    def _(): 
       # use obj_a and obj_b 
    return _ 
 
@decorator 
def foo(): 
    ... 

但是,简单地编写一个返回这两个对象并让调用者使用他们喜欢的任何名称的函数几乎不再是更灵活的方法了:

def _get_a_b(): 
    a = ... 
    b = ... 
    return a, b 
 
def foo(): 
   obj_a, obj_b = _get_a_b() 
   ... 
 
def bar(): 
    a1, a2 = _get_a_b() 
    ...