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

M-V*_*M-V 4 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
Run Code Online (Sandbox Code Playgroud)

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

所以这是我的尝试(对于 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
Run Code Online (Sandbox Code Playgroud)

运行它:

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
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:

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

Alf*_*lfe 5

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

另一方面,如果您想到的更像是一个对象、一个事物(碰巧具有某些属性、方法、指令、功能等),那么您应该将其编程为一个对象、一个类。

在您的情况下,我认为实现这一点的最佳方法既不是 ;-) 我会用生成器来做到这一点:

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

incr = incrX(10)
print incr.next()
print incr.next()
Run Code Online (Sandbox Code Playgroud)