2

在 python 中,有(至少)三种不同的方法来跟踪函数的状态信息(显然,这些示例没有任何有意义的方式来使用状态信息):

面向对象类:

class foo:
    def __init__(self, start):
        self.state = start
    # whatever needs to be done with the state information

非局部变量(Python 3):

def foo(start):
    state = start
    def bar():
        nonlocal state
        # whatever needs to be done with the state information
    return bar

或功能属性:

def foo(start):
    def bar(bar.state):
        # whatever needs to be done with the state information
    bar.state = start
    return bar

我了解每种方法的工作原理,但我无法解释为什么(除了熟悉之外)您会选择一种方法而不是另一种方法。继 Python 之禅之后,类似乎是最优雅的技术,因为它消除了嵌套函数定义的需要。然而,与此同时,类可能会引入比所需更多的复杂性。

在权衡在程序中使用哪种方法时应该考虑什么?

4

0 回答 0