【发布时间】:2023-04-06 14:50:01
【问题描述】:
我正在尝试从 OOP 过渡到函数式编程。我有以下情况:(变量没有意义 - 它们只是示例)。
Funcs = namedtuple('Funcs', ('func1', 'func2'))
def thing_1(alpha, beta):
gamma = alpha+beta
def func_1(x):
return x+gamma
def func_2(x):
return x*gamma
return Funcs(func_1, func_2)
def thing_2(alpha, beta):
gamma = alpha+beta
delta = alpha*beta
def func_1(x):
return x+gamma
def func_2(x):
return x*gamma+delta
return Funcs(func_1, func_2)
现在,我们有一些代码重复:func_1 在这两件事上是相同的。这两件事也以相同的方式初始化 gamma。
如果我使用 OOP,很明显该怎么做 - 制作 BaseThing,制作 func_2 抽象,并让 Thing1 覆盖方法 func_2 和 Thing2 覆盖 func_2 方法和 __init__ (这将调用BaseThing.__init__ 然后初始化增量)。
使用闭包,这对我来说并不明显 - 做同样事情的最佳方法是什么?
【问题讨论】:
-
只需将
func_1移到thing_1和thing_2之外。 -
不能 - 它使用 gamma,它仅在 thing_1、thing_2 中定义。
-
因为 Python 已经有一个完美的对象系统,没有必要伪造一个闭包。函数式编程可以与 OO 一起工作。
标签: python oop functional-programming closures