Python中的状态变量:何时选择类,非局部变量或函数属性

时间:2018-05-23 20:00:06

标签: python class python-nonlocal function-attributes

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

OOP课程:

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的Zen,类似乎是最优雅的技术,因为它不需要嵌套函数定义。但是,与此同时,类可能会带来比所需更多的复杂性。

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

0 个答案:

没有答案