【问题标题】:Python decorator early parsing breaks a forward declarationPython 装饰器早期解析破坏了前向声明
【发布时间】:2021-01-24 21:20:37
【问题描述】:

我在一个系统中有一些对象,他们需要知道他们的下一个队列是谁。每个都有一个 do_process() 函数,完成后必须返回下一个类。

class A():
    def do_process(self):
        # dosomestuff
        return B(self)

class B():
    def do_process(self):
        # dosomestuff
        return C(self)

class C():
    def do_process(self):
        # dosomestuff
        return A(self)

a = A()
b = a.do_process()
c = b.do_process()
a2 = c.do_process()

然后我注意到我的所有函数在返回时都会做同样的事情,我真的应该为此编写一个装饰器。我想整理 do_process 中的最后一行,以明确说明它将使用装饰器返回以清楚起见,因此它看起来像这样:

@next_process(B) # tell the reader up front that the next object is a B thing
def do_process
   # do some stuff
   # next_process decorator returns an instance of B for us

在我的实现中,构造函数需要几个参数,但它总是相同的参数,因为 A、B、C 在我的代码中覆盖了一个基类。一个经典的工厂模式问题。但是,我立即遇到了麻烦,因为装饰器开始在 A 类中解析它,而 B 尚未声明。我在写装饰器方面也很垃圾,所以我写了一个工厂,希望用字符串“B”替换 B,让工厂在运行时将下一个对象提供给装饰器。但这很糟糕,因为一旦 B 完全声明,我只能将 B 类添加到我的工厂。然而,装饰者已经想要获得 B 的副本,它实际上在解析 A 的同时调用我的工厂,所以它在工厂之前调用我的工厂,或者任何人真正知道 B(A 类本身,甚至没有在工厂中注册这一点也是)。

class A()
   @next_decorate(next=factory("B"))  # <= blows up because the factory has not yet got a way to return class B
   def do_process(self)
      # do some stuff

我对为什么这在 C++ 中有效不感兴趣,我已经忘记了如何在 C++ 中编写宏和工厂。我想知道,我是否应该坚持我的长手,保持工厂的可维护性并在以后学习编写更复杂的装饰器。还是我错过了一个更 Pythonic 的解决方案来解决这样的紧密耦合?

【问题讨论】:

  • 只是按相反的顺序定义它们?
  • @juanpa.arrivillaga 这是我简单的速记解决方案,就是这样做的。这些类是 selenium 页面对象,我不想在创建引用圈时陷入困境,因此工厂模式感觉像是一条尝试的路线。

标签: python decorator


【解决方案1】:

你真的应该停止用 C++ 术语思考。通常,您几乎不需要编写工厂,只需一个简单的映射即可。预先编写装饰器,将字符串版本作为参数,但在内部使用映射。

def next_process(next_):
    def deco(func):
        def wrapper(self, *args, **kwargs):
            func(self, *args, **kwargs)
            return MAP[next_](self)
        return wrapper
    return deco

class Process:
    def __init__(self, prev_process):
        self.prev_process = prev_process

class A(Process):
    @next_process('B')
    def do_process(self):
        # dosomestuff
        return B(self)

class B(Process):
    @next_process('C')
    def do_process(self):
        # dosomestuff
        return C(self)

class C(Process):
    @next_process('A')
    def do_process(self):
        # dosomestuff
        return A(self)

MAP = {'A': A, 'B':B, 'C':C}

注意,如果你继续创建一些factory 类,同样的原则也适用。只需在内部使用该工厂即可。或者不要让它急切地评估。

【讨论】:

  • 谢谢@juanpa。这正是我所追求的,我的解释要么可以通过,要么你非常擅长谜题。扩展我省略的基类的奖励分数。我的应用程序中的每个类都是一个 Selenium 页面对象,因此我想要一个装饰器,这样一个页面就会指向另一个页面。 @next_process('A') def do_process(self): # dosomestuff return self # &lt;== return self here, don't try construct page here 注意:该解决方案构造了两次结果对象,我将上面的行更改为不这样做。还是99%的钱!发送
猜你喜欢
  • 2018-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-14
  • 2017-09-20
  • 1970-01-01
  • 1970-01-01
  • 2018-02-08
相关资源
最近更新 更多