python - 用闭包替换简单的 Python 类是否有益?

标签 python closures

我有以下 Python 类:

class class A:
    """a class that increments internal variable"""
    def __init__(self, x):
        self._x = x
    def incr(self):
        self._x = (self._x + 1) % 10
        return self._x

我听过一个演讲,建议这种只有一个构造函数和另一个方法的类真的应该被一个函数代替。

所以这是我的尝试(针对 Python 2.7):

def incrX(x): 
    """closure that increments internal variable"""
    d = {'x' : x}
    def incr():
        d['x'] = (d['x'] + 1) % 10
        return d['x'] 
    return incr

运行它:

def test1():
    """testing closure vs. class"""
    print 'class...'
    a = A(10)
    print a.incr()
    print a.incr()

    print 'closure...'
    incr = incrX(10)
    print incr()
    print incr()

$ python closure.py 
running closure experiments
class...
1
2
closure...
1
2

所以我的问题是:

用闭包替换像 A 这样的类有好处吗?只是想更好地理解闭包。

最佳答案

闭包和高阶函数的真正好处是它们可以表示程序员有时想到的东西。如果您作为程序员发现您想到的是一段代码、一个函数、一条关于如何计算某事(或做某事)的指令,那么您应该为此使用闭包。

如果,另一方面,你的想法更像是一个对象,一个东西(恰好有一些属性、方法、指令、能力等),那么你应该把它作为一个对象来编程,一个类(class)。

在你的情况下,我认为最好的实现方式都不是 ;-) 我会用生成器来做到这一点:

def incrX(i):
  while True:
    i += 1
    i %= 10
    yield i

incr = incrX(10)
print incr.next()
print incr.next()

关于python - 用闭包替换简单的 Python 类是否有益?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19090024/

相关文章:

javascript - 在闭包中保存值(value)

functional-programming - “关闭”到底是什么意思?

python - 正则表达式:匹配字符串中的多个时间戳

Python新手;拆分一个字符串

python - 如何使用 lxml 删除 html 实体(以及更多)?

python - requests.codes.ok 是否包含 304?

swift - 我的老师如何知道要在她的闭包中放入多少参数以及她如何知道 Swift 将推断出什么类型?

arrays - $0 和 $1 在 Swift 闭包中是什么意思?

python - 如何从行中获取数据到元组中

ios - 在 swift 的嵌套闭包中正确放置捕获列表