【问题标题】:How is this Python design pattern called?这个 Python 设计模式是怎么命名的?
【发布时间】:2021-03-12 14:43:31
【问题描述】:

在 ffmpeg-python 文档中,他们使用以下设计模式作为示例:

(
    ffmpeg
    .input('dummy.mp4')
    .filter('fps', fps=25, round='up')
    .output('dummy2.mp4')
    .run()
)

这个设计模式是怎么命名的,我在哪里可以找到更多关于它的信息,它的优缺点是什么?

【问题讨论】:

  • 方法链。在 Python 和其他语言中启用它的是一个返回 self 的类方法。
  • 你也可以搜索builder模式,它利用方法链来构造对象。每个链式方法都返回相同的实例类型,因此可以通过小步骤灵活构建实例。

标签: python python-3.x design-patterns python-object object-notation


【解决方案1】:

这个设计模式叫做builder,你可以在here阅读它

基本上,所有命令(运行除外)都会更改对象并将其返回自身,这样您就可以在对象继续进行时“构建”对象。

在我看来是非常有用的东西,在查询构建方面非常好,并且可以简化代码。

考虑一下您要构建的数据库查询,假设我们使用sql

# lets say we implement a builder called query

class query:
    def __init__():
        ...
    def from(self, db_name):
        self.db_name = db_name
        return self
    ....
 
q = query()
    .from("db_name") # Notice every line change something (like here change query.db_name to "db_name"
    .fields("username")
    .where(id=2)
    .execute() # this line will run the query on the server and return the output

【讨论】:

    【解决方案2】:

    这称为“方法链接”或“函数链接”。您可以将方法调用链接在一起,因为每个方法调用都会返回底层对象本身(在 Python 中由 self 表示,在其他语言中由 this 表示)。

    这是四人组builder design pattern 中使用的一种技术,您可以在其中构造一个初始对象,然后链接其他属性设置器,例如:car().withColor('red').withDoors(2).withSunroof()

    这是一个例子:

    class Arithmetic:
        def __init__(self):
            self.value = 0
    
        def total(self, *args):
            self.value = sum(args)
            return self
    
        def double(self):
            self.value *= 2
            return self
    
        def add(self, x):
            self.value += x
            return self
    
        def subtract(self, x):
            self.value -= x
            return self
    
        def __str__(self):
            return f"{self.value}"
    
    
    a = Arithmetic().total(1, 2, 3)
    print(a)  # 6
    
    a = Arithmetic().total(1, 2, 3).double()
    print(a)  # 12
    
    a = Arithmetic().total(1, 2, 3).double().subtract(3)
    print(a)  # 9
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-25
      • 1970-01-01
      相关资源
      最近更新 更多